package com.hualai.plug.doorbell.cmcplayer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.HLApi.CameraAPI.connection.ConnectControl;
import com.HLApi.CameraAPI.media.AudioDataProcess;
import com.HLApi.CloudAPI.CloudApi;
import com.HLApi.CloudAPI.ControlHandler;
import com.HLApi.Dash.DashDecodeController;
import com.HLApi.Dash.DashManager;
import com.HLApi.Obj.BindableDevice;
import com.HLApi.Obj.CameraInfo;
import com.HLApi.Obj.EventItem;
import com.HLApi.utils.AnimLoading;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.hl.media.utils.Mp4Editor;
import com.hualai.R;
import com.test.hlplayer.DBPhotoLiveView;
import com.wyze.event.adapter.MyFragmentAdapter;
import com.wyze.event.cloud.WyzeEventPlatform;
import com.wyze.event.common.C;
import com.wyze.event.common.CommonMethod;
import com.wyze.event.common.Log;
import com.wyze.event.common.MessageIndex;
import com.wyze.event.common.StatIndex;
import com.wyze.event.common.WyzeStatisticsUtils;
import com.wyze.event.model.AiSelectDevice;
import com.wyze.event.model.EventModel;
import com.wyze.event.model.WyzeEventSelectModel;
import com.wyze.event.utils.AlarmVideoProgress;
import com.wyze.event.utils.AudioFoucsTool;
import com.wyze.event.utils.DecryptionUtils;
import com.wyze.event.utils.G711Utils;
import com.wyze.event.utils.SPTools;
import com.wyze.event.utils.TitleBarUtil;
import com.wyze.event.utils.WyzeEventDisplayUtils;
import com.wyze.event.widget.EventBottomFeedbackDialog;
import com.wyze.event.widget.EventBottomSuccessDialog;
import com.wyze.event.widget.FragmentVideoPlayer;
import com.wyze.event.widget.OneBtnDialog;
import com.wyze.event.widget.RoundProgressBar;
import com.wyze.event.widget.TwoBtnDialog;
import com.wyze.event.widget.WyzeCMCPromptManger;
import com.wyze.event.widget.WyzeEventShareDialog;
import com.wyze.platformkit.base.WpkBaseActivity;
import com.wyze.platformkit.base.WpkBaseApplication;
import com.wyze.platformkit.base.receiver.MessageEvent;
import com.wyze.platformkit.config.WpkRouteConfig;
import com.wyze.platformkit.devicemanager.WpkDeviceManager;
import com.wyze.platformkit.model.DeviceModel;
import com.wyze.platformkit.router.WpkRouter;
import com.wyze.platformkit.utils.common.WpkFontsUtil;
import com.wyze.platformkit.utils.common.WpkToastUtil;
import com.wyze.platformkit.utils.statistics.WpkStatisticsAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.mp4parser.muxer.Movie;
import org.mp4parser.muxer.Track;
import org.mp4parser.muxer.container.mp4.MovieCreator;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import okhttp3.Call;

import static java.lang.Thread.sleep;

/**
 * 报警视频播放
 * Created by hz on 2018/12/12.
 * Modify by lmy on 2019/10/03
 */
@Route(path = "/db_event/dBKvsEventPlayerActivity")
public class DBKvsEventPlayerActivity extends WpkBaseActivity implements SurfaceHolder.Callback {

    public static final String TAG = "DBKvsEventPlayerActivity ";
//    public static final String NEUTRIF_PRO_SEMI_BOLD_ITALIC = "fonts/Neutrif-Pro-Semi-Bold-Italic.otf";
//    public static final String NEUTRIF_PRO_REGULAR_ITALIC = "fonts/Neutrif-Pro-Regular-Italic.otf";
//    public static final String NEUTRIF_PRO_OTF = "fonts/Neutrif-Pro.otf";

    public static final String ALARMLIST = "ALARMLIST";
    public static final String CURRENTPOSITION = "CURRENTPOSITION";
    public static final String EVENTREQUESTMAC = "EVENTREQUESTMAC";//请求的mac
    public static final String EVENTREQUESTTAG = "EVENTREQUESTTAG";//请求的TAG
    public static final String EVENTREQUESTSTARTTIME = "EVENTREQUESTSTARTTIME";//请求的starttime

    public static final int RESULT_OK = 3000;
    private static final int CHANGE_START_TIME = 3100;
    public static final int MSG_PREPARE_PLAY = 3101;
    private static final int MSG_START_PLAY = 3109;
    private static final int MSG_HIDE_BG_PIC = 3110;
    private static final int MSG_HIDE_LAND_BAR = 3111;
    private static final int MSG_SET_VIDEO = 3112;
    private static final int MSG_HIDE_PORTRAIT_PLAY_ICON = 3113;
    private static final int RANMAXNUM = 100;
    private static final int FEEDBACK_TIME = 14;


    private String carrier = android.os.Build.MANUFACTURER;//手机机型

    private List<FragmentVideoPlayer> fragments;
    private TextView tv_startTime, tv_alarm_startTime_land, tv_alarm_endTime_land, tv_title, tv_video_time/*,tv_jump_live,tv_jump_playback*/;
    private ImageView iv_play_icon, iv_sound, iv_share, iv_delete/*, iv_alarm_video_play_in_bar*/, iv_full_screen, iv_alarm_download,
            iv_default_bg, iv_alarm_play_icon_land_bottom, iv_alarm_sound_land, iv_fillscreen_land, iv_alarm_living_land, iv_alarm_playback_land, iv_back_land;
    private SurfaceView sfv_videoplay;
    private SurfaceHolder surfaceHolder;
    //    private LinearLayout cl_jump;
    private FrameLayout frameLayout;
    private ViewPager viewpager;
    private MyFragmentAdapter titleAdapter;
    private MediaPlayer mPlayer = null;
    private SeekBar seekBar, sb_alarm_seekbar_land;
    private RelativeLayout rl_player_zone, rl_operator, rl_content, rl_sound,
            rl_control_bar, rl_live_stream, rl_jump_to_play_back,
            rl_alarm_player_delete;
    private FrameLayout rl_title_bar;
    private File videoFile = null;
    private PlayerHandler playerHandler;
    //    private PowerManager.WakeLock wakeLock;//电源管理锁屏对象
    protected boolean isOnError = false;
    private AudioTrack mPCMAudioTrack;
    private PlayAudioThread playAudioThread;
    private boolean hasAudioTrack = false; // 是否获取到音轨
    private LinearLayout ll_video_player_bottom_bar, ll_right_land;
    private RelativeLayout mLandSeekRl;
    private boolean isFullScreen = false;
    private boolean isAudioEnable = false;//是否有声音判断
    private boolean isPause = false, isPlayOver = false; // 是否暂停
    private OrientationEventListener mOrientationListener; // 屏幕方向改变监听器
    private boolean mIsLand = false; // 是否是横屏
    private boolean mClick = false; // 是否点击
    private boolean mClickLand = true; // 点击进入横屏
    private boolean mClickPort = true; // 点击进入竖屏
    private boolean isReverseLand = false;
    private boolean isClickFullScreen = false;
    private float currentPosition = 0;
    private boolean isCurrentPage = true, isPageWillScroll = false;
    private boolean isUpdateProgress = true;
    private boolean isProgUpdaterRunning = false;
    private boolean isFromPush = false;
    private boolean hasSwipedViewPager = false;
    private static String alarmID = "";
    private int MODE = 0;   //原始
    private int MODE_SCALE = 1;
    private int MODE_DRAG = 2;
    private boolean isZoom = false;
    private int scaleMaxValue = 4;
    private int screenWidth = 0;
    private int screenHeight = 0;
    private int scaleWidth = 0;   //控件缩放的宽度
    private int scaleHeight = 0;  //控件缩放的高度
    private boolean isDouble = false;

    //下载
    private int filmLength = 0;//文件大小
    private int downFileLength = 0;//当前下载的总量
    private long currentmills = 0;//一秒前的时间
    private int olddownFileLength = 0;//一秒前下载的总量
    private int downloadFaileCount = 0;//下载失败的次数


    //数据
    public EventItem mRecord;//当前数据类型
    public ArrayList<EventItem> recordList = new ArrayList<>();//数据队列
    public int currentIndex = 0;//当前位置
    private String totalDuration;//本次视频长度
    private RelativeLayout mLandTitleBar;//全屏上方bar
    private TextView mLandDeviceTv;//全屏设备名
    private TextView mLandInfoTv;//全屏拓展信息展示


    //加载更多
    private View rl_loading;//加载中  UI
    private long loadTime;//加载的起始时间
    private String mMac, mTag;//当前允许的加载更多的类型
    private boolean ishasMore = true;//是否还有更多可以允许加载
    private boolean isCanLoadMore = false;//是否准备好可以加载更多
    private long lastLoadTime;//上次加载更多的请求事件
    private boolean isDowload;
    String galleryPath = Environment.getExternalStorageDirectory()
            + File.separator + Environment.DIRECTORY_DCIM
            + File.separator;

    //下载重新（不冲突）
    private boolean isDownloadFileFinsh = false;//下载文件是否完成
    private boolean isDownloadFileFailed;//是否下载视屏失败
    private int downloadFaileCounts;//下载失败的次数
    private RoundProgressBar mShareDownloadRpb;
    private final int SETDEFAULTIMAGE = 1;
    private final int HIDEBAR = 2;
    private final int CLICK_SINGLE_VIDEO = 3;
    private static final int PLAY_SOUND = 22200;
    public static final int MSG_SEEK_UPDATE = 30;
    public static final int MSG_DISMISS_MASK = 203;
    private boolean isFristIn = true;
    private boolean isTranscodingFailedG711 = false;//转G711失败
    private Thread picThread;
    private Bitmap bitmapsFromVideo;
    private String shareTitle;
    private String shareUrl;
    private RelativeLayout download_rl_loading;
    private String down_videoUrl;
    private String down_fileName;
    private String videoPath;
    private boolean isFirst = false;
    private TextView tv_improve_share;
    private TextView tv_improve_text;
    private RelativeLayout tv_improve_layout; //share布局
    private RelativeLayout tv_improve_thanks;
    private SharedPreferences.Editor spEdit; //保存是否点击过share
    private SharedPreferences sharedPreferences;
    private String is_share = "share";
    private WyzeEventShareDialog wyzeEventShareDialog;

    private ArrayMap<String, Boolean> bindlists = new ArrayMap<>();
    private JSONArray mac;
    private EventBottomFeedbackDialog dialog;
    private long duration = -1;

    /*******************Complete Motion area*********************************/
    private int mVideoMode = -1;//视频播放0, dash living 1  ,dash playback 2
    private int isLive = 0;

    private final int VIDEO_LOCAL = 0;
    private final int VIDEO_COMMON = 0;
    private final int VIDEO_DASH_LIVING = 1;
    private final int VIDEO_DASH_PLAYBACK = 2;
    private final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";//按下home键

    private boolean isChangePage = false;
    private boolean isMergeVideo = false;
    private boolean isShare = false;
    private String systemPath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "wyze" + File.separator;
    private int clickVerShowTimes = 0;
    private int MAX_VERSION_TIMES = 5;
    private long CLICK_TIME_LIMIT = 4000;
    private long lastClickTime = 0;
    private boolean hasReceiveIFrame = false;
    private long dashPlaybackStartTsInSec = System.currentTimeMillis() / 1000 - 60; //1562706030L;
    private long DASH_PLAYBACK_DURATION_SEC = 60;//60 * 10
    private long dashPlaybackEndTsInSec = 0L;

    private final int CONNECT_STATUS_ERROR = 4; // 连接失败/错误
    private final int CONNECT_STATUS_PLAY = 5; // 播放状态
    private final int CONNECT_STATUS_NO_PLAYBACK_DATA = 6; // 回放无数据
    private final int CONNECT_STATUS_DASH_BUFFERRING = 7; // 回放无数据
    private final int CONNECT_STATUS_DASH_PLAY = 8; // DASH 播放中
    private final int ERROR_IGNORE = 0;
    private ImageView iv_video_display;
    private final int SET_PLAYBACK_SCREEN = 1200;
    private long lastFrameUs = 0L;
    private boolean isDashPlayError = false;
    private boolean isOwner = true;
    private final int TIME_OFFSET = (5 * 60 * 1000);    //Calculate duration of between event A and B from common device
    private boolean isHasSDCard = false;
    public static String CMC_IS_LIVE = "CMC_IS_LIVE";
    public static final String IS_START_CMC_SUCCESS = "IS_START_CMC_SUCCESS";


    /*********************Complete Motion area end****************************/

    private String deviceModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ver=" + C.EVENTS_VERSION);
        TitleBarUtil.enableTranslucentStatus(this);
        setContentView(R.layout.db_activity_wyze_event_player);

        ARouter.getInstance().inject(this);
        setResult(1326);

        playerHandler = new PlayerHandler();
        screenWidth = CommonMethod.getHasVirtualKeyWidth(getActivity());//CommonMethod.getScreenWidth(DBKvsEventPlayerActivity.this);
        screenHeight = isFullScreen ? CommonMethod.getHasVirtualKeyHeight(getActivity()) : screenWidth * 9 / 16;//CommonMethod.getScreenHeight(DBKvsEventPlayerActivity.this);

        deviceModel = getIntent().getStringExtra("deviceModel");
        initUI();
        isFirst = true;
        WyzeCMCPromptManger.getInstance().init(getActivity()).getCmcPrompt();//CMC 弹窗
        if (!isPush()) {
            initViewPager();
            onClick();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        isUpdateProgress = true;
        playerHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startAutoRotateListener();
            }
        }, 1000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        duration = System.currentTimeMillis() / 1000;
        WyzeStatisticsUtils.pageStart(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_FIREBASE, 1, TAG);
        keepScreenOn();
        if (playerHandler == null) {
            playerHandler = new PlayerHandler();
        }
        ConnectControl.instance(mMac).setUIHandler(playerHandler);
        setScreen(isFullScreen);
        Log.i(TAG, "mVideoModel:"+mVideoMode);
        if (mVideoMode == VIDEO_COMMON) {
            if (isFirst) {
                Log.i(TAG, "第一次进入直接走");
                isFirst = false;
                //是否为推送，推送走推送流程，
                if (isFromPush) {
                    return;
                }
                //自动播放
                setVideoData("autoplay");
            } else {
                Log.i(TAG, "onResume进入");
                //是否为推送，推送走推送流程，
                if (isFromPush) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(700);
                            //自动播放
                            setVideoData("autoplay");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else {
            Log.i(TAG, "onResume, isChangePage: " + isChangePage);
            if (isChangePage) {
                isChangePage = false;
                isAudioEnable = SPTools.getBooleanValue(DBKvsEventPlayerActivity.this, SPTools.KEY_ALARM_VOICE + mMac, false);
                setAudioEnable(isAudioEnable);
                resumePlay();
            } else {
                lastFrameUs = 0;
                //是否为推送，推送走推送流程，
                if (isFromPush) {
                    return;
                }
                com.HLApi.utils.C.isEnableHardDecode = SPTools.getBooleanValue(getApplicationContext(), SPTools.KEY_ENABLE_HARD_DECODER, com.HLApi.utils.C.isEnableHardDecode);
                ConnectControl.instance(mMac).setCalibrationType(SPTools.getIntValue(getApplicationContext(), SPTools.KEY_CALIBRATION + "" + C.currentCamMac, CameraInfo.CALIBRATION_TYPE_OFF));
                DashDecodeController.instance(mMac).setUiHandler(playerHandler);
                DashDecodeController.instance(mMac).setDeviceModel(deviceModel);
                if (!DashManager.instance().isDownloadOver()) {
                    setDashMode(mVideoMode, false);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEvent(MessageEvent event) {
        Log.i(TAG, "event msf= " + event.getMsg());
        Log.i(TAG, "event content= " + event.getContent());
        switch (event.getMsg()) {
            case IS_START_CMC_SUCCESS:
                finish();
                break;
        }
    }

    private void getSdCardInfo() {
        CloudApi.instance().getDeviceCustomData(playerHandler, mRecord.getDeviceMac(), mRecord.getEventModel(), "DeviceParams");
    }

    private void resumePlay() {
        keepScreenOn();
        if (!iv_play_icon.isSelected()) {
            iv_default_bg.setVisibility(View.GONE);
            DashDecodeController.instance(mMac).resumeDashCallBack();
//            DashDecodeController.instance(mMac).setIsParseVideo(true);
//            DashDecodeController.instance(mMac).startImageThread();
            long tsInMs = DashManager.instance().prog2TsInMs(isFullScreen ? sb_alarm_seekbar_land.getProgress() : seekBar.getProgress(), isFullScreen ? sb_alarm_seekbar_land.getMax() : seekBar.getMax());
            DashManager.instance().resumePlaying(tsInMs);
        }
    }

    public void setDashMode(int videoMode, boolean hasReceiveIFrame) {
        this.hasReceiveIFrame = hasReceiveIFrame;
        this.mVideoMode = videoMode;
        uiForPlayStop();
        Log.d(TAG, "setDashMode: " + (videoMode == VIDEO_DASH_LIVING ? "VIDEO_DASH_LIVING" : "VIDEO_DASH_PLAYBACK"));
        switch (videoMode) {
            case VIDEO_LOCAL: {

            }
            break;
            case VIDEO_DASH_LIVING: {
                clear();
                DashDecodeController.instance(mMac).setIsParseVideo(true);
                DashDecodeController.instance(mMac).resumeDashCallBack();
                DashDecodeController.instance(mMac).startImageThread();
                setViewStatus(VIDEO_DASH_LIVING, true, ERROR_IGNORE);
                getKVSURLLIVEANDPLAYBACK(mMac, mRecord.getEventModel(), mRecord.getStart_time(), true);
            }
            break;
            case VIDEO_DASH_PLAYBACK: {
                clear();
                DashDecodeController.instance(mMac).setIsParseVideo(true);
                DashDecodeController.instance(mMac).resumeDashCallBack();
                DashDecodeController.instance(mMac).startImageThread();
                setViewStatus(VIDEO_DASH_PLAYBACK, true, ERROR_IGNORE);
                dashPlaybackStartTsInSec = mRecord.getStart_time() / 1000;
                dashPlaybackStartTsInSec = (dashPlaybackStartTsInSec != 0f ? dashPlaybackStartTsInSec : mRecord.getEvent_ts() / 1000);
                dashPlaybackEndTsInSec = dashPlaybackEndTsInSec != 0L ? dashPlaybackEndTsInSec : mRecord.getEnd_time() / 1000;
                Log.e(TAG, "setDashMode: curr=" + dashPlaybackStartTsInSec + "----" + dashPlaybackEndTsInSec);
                if (dashPlaybackEndTsInSec != 0f) {
                    getKVSURLPlayback(mMac, mRecord.getEventModel(), dashPlaybackStartTsInSec, dashPlaybackEndTsInSec);
                } else {
                    getKVSURLPlayback(mMac, mRecord.getEventModel(), dashPlaybackStartTsInSec, dashPlaybackStartTsInSec + DASH_PLAYBACK_DURATION_SEC);
                }
            }
            break;
        }
    }

    private void getDeviceInfo() {
        CloudApi.instance().getV2DeviceInfo(playerHandler, mRecord.getDeviceMac(), mRecord.getEventModel());
    }

    private void getKVSURLLIVEANDPLAYBACK(String mac, String deviceModel, long startTime, boolean isShowLoading) {
        AnimLoading.cancel();
        AnimLoading.show(getActivity(), playerHandler, rl_content, 1000 * 60, "getKVSURLLIVE");
        startTime = startTime / 1000;
        long endTime = startTime + (5 * 60);
        CloudApi.instance().getKVSURLLive(playerHandler, mac, deviceModel, startTime, endTime);
    }

    private void getKVSURLPlayback(String mac, String model, long startTime, long endTime) {
        AnimLoading.cancel();
        AnimLoading.show(getActivity(), playerHandler, rl_content, 1000 * 60, "getKVSURLPlayback");
        CloudApi.instance().getKVSURLPlayback(playerHandler, mac, model, startTime, (endTime - startTime) <= 0 ? (startTime + 60) : endTime);
    }

    // FIXME: 2019/7/19 待补充
    private void setViewStatus(int status, boolean isRetry, int errorCode) {
        Log.d(TAG, "setViewStatus: status=" + status);
        switch (status) {
            case CONNECT_STATUS_PLAY: { // 收到第一个I帧
                iv_full_screen.setEnabled(true);
                iv_full_screen.setAlpha(1f);
                setDurationTime(mVideoMode);
            }
            break;
            case CONNECT_STATUS_DASH_BUFFERRING: {
            }
            break;
            case VIDEO_DASH_LIVING:
                setDurationUI(VIDEO_DASH_LIVING);
                break;
            case VIDEO_DASH_PLAYBACK:
                setDurationUI(VIDEO_DASH_PLAYBACK);
                break;
            case CONNECT_STATUS_DASH_PLAY: {
                iv_full_screen.setEnabled(true);
                iv_full_screen.setAlpha(1f);
                setDashSeekBarInfo();
                hidePlayIcon();
                iv_play_icon.setImageDrawable(getResources().getDrawable(R.drawable.selector_play_video, null));
                iv_play_icon.setSelected(false);
                iv_default_bg.setVisibility(View.GONE);
            }
            break;
        }
    }

    private void setDurationTime(int dashMode) {
        if (DashManager.instance().getDmStartTsInMs() != 0) {
            String startStr = CommonMethod.getCounterTimeString(DashManager.instance().getDmStartTsInMs() / 1000, "HH:mm:ss");
            String endStr = CommonMethod.getCounterTimeString(DashManager.instance().getDmEndTsInMs() / 1000, "HH:mm:ss");
            Log.i(TAG, "setDurationTime,startTime: " + startStr + ", endTime: " + endStr);
            if (dashMode == VIDEO_DASH_PLAYBACK) {
                tv_startTime.setText(startStr.concat(" / ").concat(endStr));
                tv_alarm_startTime_land.setText(startStr.concat(" / ").concat(endStr));
            }
        } else {
            Log.i(TAG, "dash startTime is 0");
            hasReceiveIFrame = false;
            lastFrameUs = 0;
        }
    }


    private void setDurationUI(int dashMode) {
        if (dashMode == VIDEO_DASH_PLAYBACK) {
            tv_startTime.setTextColor(Color.parseColor("#FF7E8D92"));
            tv_startTime.setBackground(null);
            tv_alarm_startTime_land.setTextColor(Color.parseColor("#FF7E8D92"));
            tv_alarm_startTime_land.setBackground(null);
        }
        if (dashMode == VIDEO_DASH_LIVING) {
            tv_startTime.setText(getString(R.string.wyze_live));
            tv_startTime.setTextColor(ContextCompat.getColor(DBKvsEventPlayerActivity.this, R.color.white));
            tv_startTime.setBackground(getDrawable(R.drawable.shape_red_round_block_live));
            tv_alarm_startTime_land.setText(getString(R.string.wyze_live));
            tv_alarm_startTime_land.setBackground(getDrawable(R.drawable.shape_red_round_block_live));
        }
    }

    private void updateDurationTime(String startTime) {
        if (mVideoMode == VIDEO_DASH_PLAYBACK) {
            String endStr = CommonMethod.getCounterTimeString(DashManager.instance().getDmEndTsInMs() / 1000, "HH:mm:ss");
            if (DashManager.instance().getDmStartTsInMs() != 0) {
                tv_startTime.setText(startTime.concat(" / ").concat(endStr));
                tv_alarm_startTime_land.setText(startTime.concat(" / ").concat(endStr));
            }
        }
    }

    private void setDashSeekBarInfo() { // TODO 在切换MPD时需要刷新这些信息
        Log.d(TAG, "setDashSeekBarInfo: mVideoMode= " + (mVideoMode == VIDEO_DASH_LIVING ? "VIDEO_DASH_LIVING" : "VIDEO_DASH_PLAYBACK"));
        if (mVideoMode == VIDEO_DASH_PLAYBACK) {
            setDurationTime(VIDEO_DASH_PLAYBACK);
            seekBar.setMax((int) DashManager.instance().getDuration());
            sb_alarm_seekbar_land.setMax((int) DashManager.instance().getDuration());
        } else {
            if (seekBar.getProgress() == seekBar.getMax()) {
                setDurationUI(VIDEO_DASH_LIVING);
            }
        }
    }

    private void clearKeepScreenOn() {
        try {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "onStop screen on: " + e.getMessage());
        }
    }

    private void keepScreenOn() {
        try {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");

        AnimLoading.cancel();
        if (mVideoMode == VIDEO_COMMON) {
            if (mPlayer != null && mPlayer.isPlaying()) {
                isPause = true;
                mPlayer.stop();
                iv_default_bg.setVisibility(View.VISIBLE);
            }
            if (playAudioThread != null) {
                playAudioThread.setPause(true);
            }
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                if (mPCMAudioTrack != null) {
                    mPCMAudioTrack.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            setAudioSilence(true);
        }
    }

    @Override
    public void onStop() {
        Log.e(TAG, "onStop");
        super.onStop();
        clearKeepScreenOn();
        if (mVideoMode == VIDEO_COMMON) {
            isUpdateProgress = false;
            clearSeekbarUpdater();
            if (mPlayer != null) {
                mPlayer.release();
                mPlayer = null;
            }
            if (frameLayout != null) {
                frameLayout.removeAllViews();
            }

            //停止下载
            if (AlarmVideoProgress.isDownload) {
                AlarmVideoProgress.stopDownloadVideo = true;
            }
        } else {
            isChangePage = true;
            pausePlay();
        }
        statisticDuration();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        currentIndex = 0;
        FragmentVideoPlayer.isTheFirstTimeComeInVidepPlayer = true;
        playerHandler.removeCallbacksAndMessages(null);
        try {
            if (mOrientationListener != null) {
                mOrientationListener.disable();
            }
            unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mVideoMode == VIDEO_COMMON) {
            if (mPCMAudioTrack != null) {
                mPCMAudioTrack.release();
            }
        } else {
            clear();
            playerHandler = null;
            pretendRelease();
        }
        //回收handler
        System.gc();

    }

    private void clear() {
        DashDecodeController.instance(mMac).pauseDashCallBack();
        DashManager.instance().pausePlaying();
        DashManager.clear();
        DashDecodeController.instance(mMac).stopDash();
        DashDecodeController.instance(mMac).clearCache();
        DashDecodeController.instance(mMac).controlHandler.removeCallbacksAndMessages(null);
        playerHandler.removeMessages(com.HLApi.utils.MessageIndex.REFRESH_VIDEO_INFO);
        lastFrameUs = 0;
        dashPlaybackStartTsInSec = 0L;
        dashPlaybackEndTsInSec = 0L;
        com.HLApi.utils.CommonMethod.deleteFiles(com.HLApi.utils.C.dashTemp);
        com.HLApi.utils.CommonMethod.deleteFiles(com.HLApi.utils.C.lastDashImagePath);
    }

    private void pretendRelease() {
        try {
            if (iv_video_display != null) {
                iv_video_display.setImageBitmap(null);
            }
        } catch (Exception e) {
            Log.e(TAG, "message = " + e.getMessage());
        }
        System.gc();
    }

    @Override
    public void onBackPressed() {
        if (isFullScreen) {
            isDouble = false;
            setScreen(false);
        } else {
            goBack();
        }
    }

    private void setVideoData(String tag) {
        Log.i(TAG, "setVideoData  tag = " + tag);
        if (playerHandler.hasMessages(MSG_SET_VIDEO)) {
            playerHandler.removeMessages(MSG_SET_VIDEO);
        }
        playerHandler.sendEmptyMessageDelayed(MSG_SET_VIDEO, 500);
    }

    private void setVideoData(boolean isSwippedViewPager) {
        Log.i(TAG, "setVideoData     isSwippedViewPager=" + isSwippedViewPager);
        Log.i(TAG, "AlarmVideoProgress.isDownload  " + AlarmVideoProgress.isDownload);
        Log.i(TAG, "AlarmVideoProgress.stopDownloadVideo  " + AlarmVideoProgress.stopDownloadVideo);
        //去除所有消息
        if (playerHandler != null) {
            playerHandler.removeMessages(MSG_SET_VIDEO);
        }
        //去掉下载UI
        if (AlarmVideoProgress.isDownload) {
            AlarmVideoProgress.stopDownloadVideo = true;
        }
//        uiForPlayStop();

        File videofile = new File(mRecord.getVideoFilePath(C.newVideoPath));

        Log.i(TAG, "videofile is exists:"+videofile.exists());
        if (!videofile.exists()) {
            fragments.get(currentIndex).showBgPic(false);
            uiForAiHintVisible(false);
            getFileURL();
        } else {
            videoFile = videofile;
            if(isDBModel()){
                rotateDBFile();
            }else{
                playerHandler.sendEmptyMessage(MSG_PREPARE_PLAY);
            }

        }
//        changeFontStyle(true);
        if (mRecord.getRead_state() == 0) {
            sendSetRead();
        } else if (mRecord.getRead_state() == 1) {
//            changeFontStyle(false);
        }
        String timeText = (mRecord.isPerson() ? getString(R.string.wyze_person) : mRecord.getEventAlarmValue(getActivity()))
                + " at " + CommonMethod.getSystemTime(mRecord.getEvent_ts(), getActivity());
        tv_video_time.setText(timeText);
        mLandInfoTv.setText(timeText);
        DeviceModel.Data.DeviceData device = WpkDeviceManager.getInstance().getDeviceModelById(mRecord.getDeviceMac());
        String devicename = device != null ? device.getNickname() : mRecord.getDeviceMac();
        tv_title.setText(devicename);
        mLandDeviceTv.setText(devicename);
    }

    /**
     * 未读状态进行请求
     */
    private void sendSetRead() {
        /**
         * read_state (integer): 已读未读状态 1=已读 0=未读
         */
        JSONArray jsonArray = new JSONArray();
        String eventID = mRecord.getEventID();
        jsonArray.put(eventID);

        WyzeEventPlatform.getInstance().setReadStateList(getContext(), mRecord.getDeviceMac(), 1, jsonArray, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(response);
                    String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                    String data = jsonObject.has("data") ? jsonObject.getString("data") : null;
                    if (code.equals("1")) {
                        recordList.get(currentIndex).setRead_state(1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 设置字体样式
     */
    private void changeFontStyle(boolean isChangeFont) {
        AssetManager mgr = getAssets();
        Typeface tf = null;
        if (isChangeFont) {
            tf = Typeface.createFromAsset(mgr, WpkFontsUtil.TTNORMSPRO_BOLD);
        } else {
            tf = Typeface.createFromAsset(mgr, WpkFontsUtil.TTNORMSPRO_NORMAL);
        }
        tv_video_time.setTypeface(tf);
        mLandInfoTv.setTypeface(tf);
    }

    /**
     * 是否推送 推则请求详情  不初始化， 不推直接初始化
     *
     * @return 是否推送
     */

    boolean isPush() {
        rl_loading = findViewById(R.id.rl_loading);
        String alarm_id = getIntent().getStringExtra("alarm_id");
        String device_mac = getIntent().getStringExtra("device_mac");
        Log.d(TAG, "Push __  Player     alarm_id=" + alarm_id + "   device_mac=" + device_mac);
        if (alarm_id != null && !alarm_id.isEmpty() && device_mac != null && !device_mac.isEmpty()) {
//            setProgressing(true);
            WyzeEventPlatform.getInstance().getEventInfo(getContext(), alarm_id, device_mac, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    setProgressing(false);
                    finish();
                    Toast.makeText(getActivity(), getString(R.string.failed), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(String response, int id) {
                    setProgressing(false);
                    JSONObject jsonObject = null;

                    try {
                        jsonObject = new JSONObject(response);
                        String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                        String data = jsonObject.has("data") ? jsonObject.getString("data") : null;

                        //推送请求报警视频
                        if (code.equals("1")) {
                            Log.i(TAG, "get notification info  was succeed");
                            setProgressing(false);
                            EventItem recordItem = parseJsonForInfo(new JSONObject(data));
                            if (recordList == null) {
                                recordList = new ArrayList<>();
                            }

                            if (recordItem.getEvent_value().equals("13")) {

                                if (recordItem.getStart_time() > 0 && recordItem.getEnd_time() > 0) {
                                    recordItem.setLive(0);
                                } else {
                                    recordItem.setLive(1);
                                    long endTime = (recordItem.getStart_time() + TIME_OFFSET);
                                    if (System.currentTimeMillis() >= endTime) {
                                        Log.i(TAG, "the event is not full motion live,startTime:" + startTurnTime);
                                        recordItem.setEnd_time(endTime);
                                        recordItem.setLive(0);
                                    }
                                }
                            } else {
                                recordItem.setStart_time(recordItem.getEvent_ts());
                            }
                            recordList.add(recordItem);
                            mRecord = recordItem;
                            initViewPager();
                            onClick();
                            if (mVideoMode == VIDEO_COMMON) {
                                playerHandler.sendEmptyMessage(MSG_SET_VIDEO);
                            }
                        } else {
                            Log.i(TAG, "CLOUD_GET_EVENT_INFO  fail");
                            finish();
                            Toast.makeText(getActivity(), getString(R.string.failed), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        finish();
                        Toast.makeText(getActivity(), getString(R.string.failed), Toast.LENGTH_SHORT).show();
                    }
                }
            });
            isFromPush = true;
            return true;
        } else {
            isFromPush = false;
            return false;
        }
    }


    private int oldRotate = 0;
    private long startTurnTime = 0;

    //横竖屏感应
    private int convert2Orientation(int rotation) {
        int orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        if (((rotation >= 0) && (rotation <= 45)) || (rotation > 315)) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        } else if ((rotation > 45) && (rotation <= 135)) {
            isReverseLand = true;
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
        } else if ((rotation > 135) && (rotation <= 225)) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        } else if ((rotation > 225) && (rotation <= 315)) {
            isReverseLand = false;
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        }
        return orientation;
    }

    private boolean isAutoRotateEnabled = false;
    private int currentOrientation = -1;

    private final void startAutoRotateListener() {
        mOrientationListener = new OrientationEventListener(this) {
            @SuppressLint("WrongConstant")
            @Override
            public void onOrientationChanged(int rotation) {

                if ((System.currentTimeMillis() - startTurnTime) > 800) {
                    startTurnTime = System.currentTimeMillis();
                } else {
                    return;
                }
                try {
                    isAutoRotateEnabled = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION) == 1;
//                    Log.d(TAG, "==========rotation=====" + rotation);
                    if (isAutoRotateEnabled) {
//                        Log.i(TAG, "onOrientationChanged is " + rotation);

                        if (rotation == OrientationEventListener.ORIENTATION_UNKNOWN) {
                            Log.i(TAG, "onOrientationChanged is " + rotation);
                            return;
                        }
                        int orientation = convert2Orientation(rotation);
                        // 方向没有变化,跳过
                        if (orientation == currentOrientation) {
                            return;
                        }
                        currentOrientation = orientation;
                        if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ||
                                currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
                            setScreen(false);
                        } else {
                            setScreen(true);
                        }
                        DBKvsEventPlayerActivity.this.setRequestedOrientation(currentOrientation);

                    }
                } catch (Settings.SettingNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
        mOrientationListener.enable();
    }


    private void onClick() {
        tv_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long currentClickTime = System.currentTimeMillis();
                if (lastClickTime == 0) {
                    lastClickTime = currentClickTime;
                }
                long elapsedTime = currentClickTime - lastClickTime;
                if (elapsedTime < CLICK_TIME_LIMIT) {
                    clickVerShowTimes++;
                    if (MAX_VERSION_TIMES == clickVerShowTimes) {
                        if (C.isShowVersion) {
                            Toast.makeText(DBKvsEventPlayerActivity.this, C.EVENTS_VERSION, Toast.LENGTH_SHORT).show();
                        }
                        clickVerShowTimes = 0;
                    }
                } else {
                    clickVerShowTimes = 0;
                    lastClickTime = 0;
                }
            }
        });
        rl_live_stream.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonMethod.isFastDoubleClick(500)) {
                    DeviceModel.Data.DeviceData deviceModelById = WpkDeviceManager.getInstance().getDeviceModelById(mRecord.getDeviceMac());
                    if (deviceModelById != null) {
                        isChangePage = true;
                        Log.e(TAG, "iv_jump_live: portrait screen to live page");
                        WpkRouter.getInstance().build(BindableDevice.MODEL_CAMERA_COMMON + WpkRouteConfig.open_plugin)
                                .withString("deviceMac", mRecord.getDeviceMac())
                                .withBoolean("isPlayback", false)
                                .withLong("startTime", mRecord.getStart_time())
                                .withInt("EnterMode", 3)
                                .navigation();
                        WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_ALL, 1,
                                StatIndex.WYZE_CAM_EVENT_LIVESTREAM);
                    } else {
                        Log.i(TAG, "iv_jump_live: The device has been deleted");
                        WpkToastUtil.showText(getString(R.string.wyze_kvs_has_been_deleted));
                    }
                }
            }
        });
        iv_alarm_living_land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonMethod.isFastDoubleClick(500)) {
                    DeviceModel.Data.DeviceData deviceModelById = WpkDeviceManager.getInstance().getDeviceModelById(mRecord.getDeviceMac());
                    if (deviceModelById != null) {
                        isChangePage = true;
                        Log.e(TAG, "iv_jump_live: landscape screen to live page");

                        WpkRouter.getInstance().build(BindableDevice.MODEL_CAMERA_COMMON + WpkRouteConfig.open_plugin)
                                .withString("deviceMac", mRecord.getDeviceMac())
                                .withBoolean("isPlayback", false)
                                .withLong("startTime", mRecord.getStart_time())
                                .withInt("EnterMode", 3)
                                .navigation();
                        WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_ALL, 1,
                                StatIndex.WYZE_CAM_EVENT_LIVESTREAM);
                    } else {
                        Log.i(TAG, "iv_jump_live: The device has been deleted");
                        WpkToastUtil.showText(getString(R.string.wyze_kvs_has_been_deleted));
                    }
                }
            }
        });

        rl_jump_to_play_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonMethod.isFastDoubleClick(500)) {
                    DeviceModel.Data.DeviceData deviceModelById = WpkDeviceManager.getInstance().getDeviceModelById(mRecord.getDeviceMac());

                    if (deviceModelById == null) {
                        Log.i(TAG, "iv_jump_playback: The device has been deleted");
                        WpkToastUtil.showText(getString(R.string.wyze_kvs_has_been_deleted));
                        return;
                    }

                    if (deviceModelById.getProduct_model().equals(EventModel.MODEL_WVOD1)) {
                        Log.i(TAG, "iv_jump_playback: The device was not supported");
                        WpkToastUtil.showText(getString(R.string.event_not_support_playback_the_camera));
                        return;
                    }
                    if (!isOwner) {
                        Log.i(TAG, "iv_jump_playback: " + getString(R.string.wyze_kvs_onwer_playback));
                        WpkToastUtil.showText(getString(R.string.wyze_kvs_onwer_playback));
                        return;
                    }

                    if (!isHasSDCard) {
                        Log.i(TAG, "iv_jump_playback: " + getString(R.string.no_micro_sd_card));
                        WpkToastUtil.showText(getString(R.string.no_micro_sd_card));
                        return;
                    }

                    isChangePage = true;
                    Log.e(TAG, "iv_jump_playback: portrait screen to playback page,is has sd card: " + isHasSDCard + ",startTime: " + mRecord.getStart_time());
                    WpkRouter.getInstance().build(BindableDevice.MODEL_CAMERA_COMMON + WpkRouteConfig.open_plugin)
                            .withString("deviceMac", mRecord.getDeviceMac())
                            .withBoolean("isPlayback", true)
                            .withLong("startTime", mRecord.getStart_time())
                            .withInt("EnterMode", 3)
                            .navigation();
                    WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_ALL, 1,
                            StatIndex.WYZE_CAM_EVENT_SD_CARD);
                }
            }
        });
        iv_alarm_playback_land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonMethod.isFastDoubleClick(500)) {
                    DeviceModel.Data.DeviceData deviceModelById = WpkDeviceManager.getInstance().getDeviceModelById(mRecord.getDeviceMac());
                    if (deviceModelById == null) {
                        Log.i(TAG, "iv_jump_playback, landscape: The device has been deleted");
                        WpkToastUtil.showText(getString(R.string.wyze_kvs_has_been_deleted));
                        return;
                    }

                    if (deviceModelById.getProduct_model().equals(EventModel.MODEL_WVOD1)) {
                        Log.i(TAG, "iv_jump_playback, landscape: The device was not supported");
                        WpkToastUtil.showText(getString(R.string.event_not_support_playback_the_camera));
                        return;
                    }
                    if (!isOwner) {
                        Log.i(TAG, "iv_jump_playback, landscape: " + getString(R.string.wyze_kvs_onwer_playback));
                        WpkToastUtil.showText(getString(R.string.wyze_kvs_onwer_playback));
                        return;
                    }

                    if (!isHasSDCard) {
                        Log.i(TAG, "iv_jump_playback, landscape: " + getString(R.string.no_micro_sd_card));
                        WpkToastUtil.showText(getString(R.string.no_micro_sd_card));
                        return;
                    }
                    isChangePage = true;
                    Log.e(TAG, "iv_jump_playback: landscape screen to playback page,is has sd card: " + isHasSDCard + ",startTime: " + mRecord.getStart_time());
                    WpkRouter.getInstance().build(BindableDevice.MODEL_CAMERA_COMMON + WpkRouteConfig.open_plugin)
                            .withString("deviceMac", mRecord.getDeviceMac())
                            .withBoolean("isPlayback", true)
                            .withLong("startTime", mRecord.getStart_time())
                            .withInt("EnterMode", 3)
                            .navigation();
                    WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_ALL, 1,
                            StatIndex.WYZE_CAM_EVENT_SD_CARD);
                }
            }
        });

        iv_fillscreen_land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回竖屏
                mClick = true;
                mIsLand = false;
                mClickPort = false;
                isFullScreen = false;
                setScreen(false);
                WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_FIREBASE, 1,
                        StatIndex.ST_ALARM_VIDEO_BACK);
            }
        });
        iv_back_land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回竖屏
                mClick = true;
                mIsLand = false;
                mClickPort = false;
                isFullScreen = false;
                setScreen(false);
                WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_FIREBASE, 1,
                        StatIndex.ST_ALARM_VIDEO_BACK);
            }
        });
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goBack();
                WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_FIREBASE, 1,
                        StatIndex.ST_ALARM_VIDEO_BACK);
            }
        });

        iv_play_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "iv_play_icon --- click");

                if (mVideoMode == VIDEO_COMMON) {
                    if (videoFile == null) {
                        setVideoData("click videofile = null");
                    } else {
                        hidePlayIcon();
                        if (iv_play_icon.isSelected()) {
                            if (isPause) {
                                isPause = false;
                                if (mPlayer == null) {
                                    initPlayer();
                                } else {
                                    mPlayer.start();
                                    continuePlay();
                                }
                                resumeSound();
                                runProgUpdater("iv_play_icon onclicked");
                                iv_play_icon.setSelected(false);
                            } else {
                                playerHandler.sendEmptyMessage(MSG_START_PLAY);
                            }
                        } else {
                            iv_play_icon.setSelected(true);
                            pausePlay();
                        }
                    }
                } else {
                    if (isDashPlayError) {
                        Toast.makeText(DBKvsEventPlayerActivity.this, getString(R.string.wyze_event_kvs_playback_url_is_null), Toast.LENGTH_SHORT).show();
                    } else {
                        hidePlayIcon();
                        isPlayOver = false;
                        if (iv_play_icon.isSelected()) {
                            iv_play_icon.setSelected(false);
                            resumePlay();
                        } else {
                            iv_play_icon.setSelected(true);
                            pausePlay();
                        }

                    }
                }
                iv_play_icon.setImageDrawable(getResources().getDrawable(R.drawable.selector_play_video, null));
            }
        });

        iv_full_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mClick = true;
                mIsLand = true;
                mClickLand = false;
                isFullScreen = true;
                isClickFullScreen = true;
                setScreen(true);
                WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_FIREBASE, 1,
                        StatIndex.ST_EVENT__CAM_EVENT_FULLSCREEN);
            }
        });
        rl_sound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isAudioEnable = !isAudioEnable;
                Log.i(TAG, "click sound icon,state is " + isAudioEnable);
                setAudioEnable(isAudioEnable);
                WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_ALL, 1,
                        StatIndex.WYZE_CAM_EVENT_SOUND);
            }
        });
        iv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mVideoMode == VIDEO_COMMON) {
                    if (mPlayer != null && mPlayer.isPlaying()) {
                        mPlayer.pause();
                        isPause = true;
                        pauseSound();
                        if (!isPlayOver) {
                            uiForPlayStop();
                        }
                    }
                    share(videoFile);
                } else {
                    if (isDashPlayError) {
                        return;
                    }
                    File file = new File(systemPath.concat(mMac).concat("/").concat(mRecord.getEventID().concat(".mp4")));
                    pauseSound();
                    pausePlay();
                    if (file.exists()) {
                        if (!isPlayOver) {
                            uiForPlayStop();
                        }
                        share(file);
                    } else {
                        if (DashManager.instance().isDownloadOver()) {
                            Log.i(TAG, "click download,the video was downloaded,to merge video");
                            //TODO merge video
                            DashManager.instance().mergeVideo(systemPath.concat(mMac).concat("/"), mRecord.getEventID().concat(".mp4"));
                        }
                        playerHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AnimLoading.show(getActivity(), playerHandler, rl_content, 1000 * 60, "click share video");
                            }
                        }, 1000);

                        isShare = true;
                        isMergeVideo = true;
                    }
                }
                WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_ALL, 1,
                        StatIndex.WYZE_CAM_EVENT_SHARE);
            }
        });
        rl_alarm_player_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteDialog();
            }
        });

        iv_alarm_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_ALL, 1,
                        StatIndex.WYZE_CAM_EVENT_DOWNLOAD);
                if (mVideoMode == VIDEO_COMMON) {
                    setViewClickable(false);
                    galleryPath = Environment.getExternalStorageDirectory()
                            + File.separator + Environment.DIRECTORY_DCIM
                            + File.separator;
                    //wyze 云下载
                    File videofile = new File(mRecord.getVideoFilePath(C.newVideoPath));
                    String videoFilePath = mRecord.getVideoFilePath(C.newVideoPath);
                    String s = galleryPath + System.currentTimeMillis() + ".mp4";
                    if (videofile.exists()) {
                        copyfile(videofile, new File(s), false);
                        Log.i(TAG, "文件拷贝成功！！");
                    } else {
                        if (!isNetworkAvailable()) {
                            Toast toast = Toast.makeText(getContext(), R.string.event_download_failed, Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.BOTTOM, Gravity.CENTER, WyzeEventDisplayUtils.dip2px(120));
                            toast.show();
                            setViewClickable(true);
                        } else {
                            if (TextUtils.isEmpty(down_videoUrl) && TextUtils.isEmpty(down_fileName)) {
                                //更新下载地址
                                WyzeEventPlatform.getInstance().getEventInfo(getContext(), mRecord.getEventID(), mRecord.getDeviceMac(), new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        JSONObject jsonObject = null;
                                        try {
                                            jsonObject = new JSONObject(response);
                                            String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                                            String data = jsonObject.has("data") ? jsonObject.getString("data") : null;

                                            if (code.equals("1") && data != null) {
                                                final EventItem ei = parseJsonForInfo(new JSONObject(data));
                                                if (CommonMethod.isStrNotNull(ei.getVideoUrl())) {
                                                    try {
                                                        new Thread() {
                                                            @Override
                                                            public void run() {
                                                                if (AlarmVideoProgress.isDownload) {
                                                                    AlarmVideoProgress.stopDownloadVideo = true;
                                                                    while (AlarmVideoProgress.isDownload) {

                                                                    }
                                                                    Log.i(TAG, "stop down");
                                                                }
                                                                down_videoUrl = ei.getVideoUrl();
                                                                down_fileName = ei.getVideoFileName();
                                                                videoPath = C.newVideoPath;
                                                                AlarmVideoProgress.downloadVideo(ei.getVideoUrl(), C.newVideoPath, ei.getVideoFileName(), playerHandler);
                                                            }
                                                        }.start();
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                } else {
                                                    Log.d(TAG, "get video file : url is null");
                                                    playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                                                    return;
                                                }
                                            } else {
                                                playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                                            }

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                            playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                                        }
                                    }
                                });
                            } else {
                                getDownloadFileURL(down_videoUrl, down_fileName);
                            }
                        }
                    }
                } else {
                    if (isDashPlayError) {
                        return;
                    }
                    File file = new File(systemPath.concat(mMac).concat("/").concat(mRecord.getEventID().concat(".mp4")));
                    if (file.exists()) {
                        Toast.makeText(DBKvsEventPlayerActivity.this, R.string.save_to_album, Toast.LENGTH_SHORT).show();
                    } else {
                        pausePlay();
                        if (DashManager.instance().isDownloadOver()) {
                            Log.i(TAG, "click download,the video was downloaded,to merge video");
                            //TODO merge video
                            AnimLoading.show(getActivity(), playerHandler, rl_content, 1000 * 60 * 10, "merge video");
                            DashManager.instance().mergeVideo(systemPath.concat(mMac).concat("/"), mRecord.getEventID().concat(".mp4"));
                        } else {
                            Log.i(TAG, "click download......");
                            //TODO to download video
                            playerHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    AnimLoading.show(getActivity(), playerHandler, rl_content, 1000 * 60 * 10, "click download video");
                                }
                            }, 1000);

                            isMergeVideo = true;
                            isShare = false;
                        }
                    }
                }

            }
        });

        SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
                if (mVideoMode == VIDEO_DASH_PLAYBACK) {
                    long ms = DashManager.instance().prog2TsInMs(seekBar.getProgress(), seekBar.getMax());
                    String startStr = CommonMethod.getCounterTimeString(ms / 1000, "HH:mm:ss");
                    updateDurationTime(startStr);
                    if (fromUser) {
                        long tsInMs = DashManager.instance().prog2TsInMs(isFullScreen ? sb_alarm_seekbar_land.getProgress() : seekBar.getProgress(), isFullScreen ? sb_alarm_seekbar_land.getMax() : seekBar.getMax());
                        String videoImagePath = DashManager.instance().getVideoImagePath(tsInMs);
//                        Log.e(TAG, "find dash playback image,ms: " + videoImagePath);
                        if (!TextUtils.isEmpty(videoImagePath)) {
                            Glide.with(DBKvsEventPlayerActivity.this).load(videoImagePath).into(iv_default_bg);
                        }
                    }
                } else if (mVideoMode == VIDEO_DASH_LIVING) {
                    if (fromUser) {
                        long tsInMs = DashManager.instance().prog2TsInMs(isFullScreen ? sb_alarm_seekbar_land.getProgress() : seekBar.getProgress(), isFullScreen ? sb_alarm_seekbar_land.getMax() : seekBar.getMax());
                        String videoImagePath = DashManager.instance().getVideoImagePath(tsInMs);
//                        Log.e(TAG, "find dash living image,ms: " + videoImagePath);
                        if (!TextUtils.isEmpty(videoImagePath)) {
                            Glide.with(DBKvsEventPlayerActivity.this).load(videoImagePath).into(iv_default_bg);
                        }
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.i(TAG, "OnProgress,onStartTrackingTouch: " + seekBar.getProgress());
                if (mVideoMode == VIDEO_COMMON) {
                    clearSeekbarUpdater();
                } else {
                    pausePlay();
                    if (mVideoMode == VIDEO_DASH_LIVING) {
                        Log.d(TAG, "live mode,slide thumbnail");
                        seekBar.setMax((int) DashManager.instance().getDuration());
                        sb_alarm_seekbar_land.setMax((int) DashManager.instance().getDuration());
                    }
                    iv_default_bg.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onStopTrackingTouch(final SeekBar seekBar) {
                Log.i(TAG, "OnProgress,onStopTrackingTouch: " + seekBar.getProgress());
                lastFrameUs = 0L;
                if (mVideoMode == VIDEO_COMMON) {
                    //other
                    if (mPlayer != null) {
                        mPlayer.seekTo(seekBar.getProgress());
                        Log.d(TAG, "onStopTrackingTouch: 竖屏 prog = " + mPlayer.getCurrentPosition() + "    " + ((float) mPlayer.getCurrentPosition() / (float) mPlayer.getDuration()));
                    }
                    runProgUpdater("seekBar onStopTrackingTouch");
                } else {
                    resumePlay();
                }
            }
        };
        seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
        sb_alarm_seekbar_land.setOnSeekBarChangeListener(onSeekBarChangeListener);

        tv_improve_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wyzeEventShareDialog = new WyzeEventShareDialog(getContext());
                wyzeEventShareDialog.setClicklistener(new WyzeEventShareDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        if (mVideoMode == VIDEO_COMMON) {
                            sendRequest(true);
                        } else {
                            sendKVSReportRequest(true);
                        }
                    }

                    @Override
                    public void doConfirmTwo() {
                        if (mVideoMode == VIDEO_COMMON) {
                            sendRequest(false);
                        } else {
                            sendKVSReportRequest(false);
                        }
                    }

                    @Override
                    public void doCancel() {
                        wyzeEventShareDialog.dismiss();
                    }
                });
                wyzeEventShareDialog.show();
            }
        });

    }

    /**
     * 判断AI控件是否显示
     */
    private void uiWriteCopywriter() {
        try {
            if (isFullScreen) {
                tv_improve_layout.setVisibility(View.GONE);
                tv_improve_thanks.setVisibility(View.GONE);
            } else {
                checkPersonFeedback();
            }
        } catch (Exception e) {
            tv_improve_layout.setVisibility(View.GONE);
            tv_improve_thanks.setVisibility(View.GONE);
        }
    }

    private void hidePlayIcon() {
        if (isFullScreen) {
            if (playerHandler.hasMessages(MSG_HIDE_LAND_BAR)) {
                playerHandler.removeMessages(MSG_HIDE_LAND_BAR);
            }
            playerHandler.sendEmptyMessage(MSG_HIDE_LAND_BAR);
        } else {
            if (playerHandler.hasMessages(MSG_HIDE_PORTRAIT_PLAY_ICON)) {
                playerHandler.removeMessages(MSG_HIDE_PORTRAIT_PLAY_ICON);
            }
            playerHandler.sendEmptyMessage(MSG_HIDE_PORTRAIT_PLAY_ICON);
        }
    }


    private void uiForAiHintVisible(boolean visible) {
        if (visible) {
//            if (mVideoMode == VIDEO_COMMON) {
            uiWriteCopywriter();
//            }
        } else {
            tv_improve_layout.setVisibility(View.GONE);
            tv_improve_thanks.setVisibility(View.GONE);
        }
    }

    private void sendRequest(boolean isSaw) {
        Log.i(TAG, "sendRequest -- isSaw =  " + isSaw);
        //AI
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (isSaw) {
            jsonArray.put(101);
        }
        try {
            JSONObject paramlist = new JSONObject();
            paramlist.put("collect_channel", "1");

            object.put("device_mac", mRecord.getDeviceMac());
            object.put("event_id", mRecord.getEventID());
            object.put("file_id", mRecord.getFile_id());
            object.put("is_correct", isSaw ? 1 : 0);
            object.put("is_collected", 1);
            object.put("remark", "");
            object.put("custom_param_list", paramlist);
            object.put("tag_list", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        wyzeEventShareDialog.dismiss();
        rl_loading.setVisibility(View.VISIBLE);
        WyzeEventPlatform.getInstance().getFeedBack(getContext(), object, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                rl_loading.setVisibility(View.GONE);
                WpkToastUtil.showText(getString(R.string.failed));
            }

            @Override
            public void onResponse(String response, int id) {
                rl_loading.setVisibility(View.GONE);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                    String data = jsonObject.has("data") ? jsonObject.getString("data") : null;
                    if (code.equals("1")) {
                        spEdit.putString(mRecord.getEventID(), is_share);
                        spEdit.apply();
                        uiWriteCopywriter();
                    } else {
                        WpkToastUtil.showText(getString(R.string.failed));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void sendRequest(boolean isSaw, boolean isCollect) {
        Log.i(TAG, "sendRequest -- isSaw =  " + isSaw);
        //AI
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (isSaw) {
            jsonArray.put(101);
        }

        try {

            JSONObject paramlist = new JSONObject();
            paramlist.put("collect_channel", "2");

            object.put("device_mac", mRecord.getDeviceMac());
            object.put("event_id", mRecord.getEventID());
            object.put("file_id", mRecord.getFile_id());
            object.put("is_correct", isSaw ? 1 : 0);
            object.put("is_collected", isCollect ? 1 : 0);
            object.put("remark", "");
            object.put("custom_param_list", paramlist);
            object.put("tag_list", jsonArray);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        WyzeEventPlatform.getInstance().getFeedBack(getContext(), object, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i(TAG, "popup send fail e = " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "popup send success response = " + response);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                    String data = jsonObject.has("data") ? jsonObject.getString("data") : null;
                    if (code.equals("1")) {
//                        spEdit.putString(mRecord.getEventID(), is_share);
//                        spEdit.apply();
//                        uiWriteCopywriter();
                    } else {
//                        WpkToastUtil.showText(getString(R.string.failed));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void sendKVSReportRequest(boolean isSaw) {
        Log.i(TAG, "sendKVSReportRequest -- isSaw =  " + isSaw);
        //AI
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (isSaw) {
            jsonArray.put(101);
        }
        try {
            JSONObject paramlist = new JSONObject();
            paramlist.put("collect_channel", "1");

            object.put("device_mac", mRecord.getDeviceMac());
            object.put("video_type", "1");
            object.put("is_correct", isSaw ? 1 : 0);
            object.put("event_id", mRecord.getEventID());
            object.put("begin_ts", mRecord.getStart_time());
            object.put("end_ts", mRecord.getEnd_time());
            object.put("tag_list", jsonArray);
            object.put("custom_param_list", paramlist);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        wyzeEventShareDialog.dismiss();
        rl_loading.setVisibility(View.VISIBLE);
        WyzeEventPlatform.getInstance().reportKvsFeedBack(getContext(), object, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                rl_loading.setVisibility(View.GONE);
                WpkToastUtil.showText(getString(R.string.failed));
            }

            @Override
            public void onResponse(String response, int id) {
                rl_loading.setVisibility(View.GONE);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                    String data = jsonObject.has("data") ? jsonObject.getString("data") : null;
                    if (code.equals("1")) {
                        spEdit.putString(mRecord.getEventID(), is_share);
                        spEdit.apply();
                        uiWriteCopywriter();
                    } else {
                        WpkToastUtil.showText(getString(R.string.failed));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    //播放按钮显示
    private void uiForPlayStop() {
        iv_play_icon.setVisibility(View.VISIBLE);
        iv_play_icon.setImageDrawable(getResources().getDrawable(R.drawable.selector_play_video, null));
        iv_play_icon.setSelected(true);
        iv_play_icon.bringToFront();

        if (isFullScreen) {
            mLandTitleBar.setVisibility(View.VISIBLE);
            mLandSeekRl.setVisibility(View.VISIBLE);
            ll_right_land.setVisibility(View.VISIBLE);
            iv_play_icon.setVisibility(View.VISIBLE);

            mLandTitleBar.bringToFront();
            mLandSeekRl.bringToFront();
            ll_right_land.bringToFront();
            iv_play_icon.bringToFront();
        } else {
            rl_operator.setVisibility(View.VISIBLE);
            rl_operator.bringToFront();
        }
        AnimLoading.cancel();
    }

    //重播放按钮显示
    private void uiForRePlayStop() {
        WyzeCMCPromptManger.getInstance().init(getActivity()).getCmcPrompt();
        //显示暂停按键
        isPlayOver = true;
        iv_play_icon.setVisibility(View.VISIBLE);
        iv_play_icon.setImageDrawable(getResources().getDrawable(R.drawable.ic_replay, null));
        iv_play_icon.setSelected(true);
        iv_play_icon.bringToFront();
        if (isFullScreen) {
            playerHandler.removeMessages(MSG_HIDE_LAND_BAR);
            mLandTitleBar.setVisibility(View.VISIBLE);
            mLandSeekRl.setVisibility(View.VISIBLE);
            ll_right_land.setVisibility(View.VISIBLE);
            iv_play_icon.setVisibility(View.VISIBLE);

            mLandTitleBar.bringToFront();
            mLandSeekRl.bringToFront();
            ll_right_land.bringToFront();
            iv_play_icon.bringToFront();
        } else {
            playerHandler.removeMessages(MSG_HIDE_PORTRAIT_PLAY_ICON);
            rl_operator.setVisibility(View.VISIBLE);
            rl_operator.bringToFront();
        }
        AnimLoading.cancel();
    }

    //音量可控状态
    private void setAudioEnable(boolean enable) {
        if (mVideoMode == VIDEO_COMMON) {
            if (mPCMAudioTrack == null) return;
        }
        setAudioSilence(!enable);
        iv_sound.setImageResource(enable ? R.drawable.ic_sound_full_motion : R.drawable.ic_sound_mute_full_motion);
        SPTools.setBooleanValue(DBKvsEventPlayerActivity.this, SPTools.KEY_ALARM_VOICE + mMac, enable);//保存实时浏览和手动录制的声音播放

    }

    //声音开关
    private void setAudioSilence(boolean isMute) {
        if (mVideoMode == VIDEO_COMMON) {
            if (mPCMAudioTrack != null) {
                mPCMAudioTrack.setVolume(isMute ? 0 : AudioTrack.getMaxVolume() * 0.8f);
            }
        } else {
            if (isMute) {
                AudioFoucsTool.abandon(getActivity().getApplicationContext(), TAG);
                AudioDataProcess.instance().stop(getApplicationContext());
            } else {
                AudioFoucsTool.request(getApplicationContext(), TAG + "   toggleAudio: isAudioOpen=");
                AudioDataProcess.instance().start(getApplicationContext(), null);
            }
        }
    }

    //加载显示
    private void setProgressing(boolean isloadding) {
        rl_loading.setVisibility(isloadding ? View.VISIBLE : View.GONE);
        rl_loading.bringToFront();
    }

    //删除弹窗
    private void deleteDialog() {
        final TwoBtnDialog tbwhd = new TwoBtnDialog(DBKvsEventPlayerActivity.this,
                getResources().getString(R.string.delete_video_title), getString(R.string.cancel),
                getString(R.string.ok));
        tbwhd.show();
        tbwhd.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                EventItem item = new EventItem();
                item.setDeviceMac(mRecord.getDeviceMac());
                item.setEventID(mRecord.getEventID());

                ArrayList<EventItem> eventItems = new ArrayList<>();
                eventItems.add(item);

                WyzeEventPlatform.getInstance().deleteEventMessage(getContext(), eventItems, "1", new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        WpkToastUtil.showText(getString(R.string.failed));
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);
                            String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                            String data = jsonObject.has("data") ? jsonObject.getString("data") : null;

                            if (code.equals("1")) {
                                recordList.remove(mRecord);
                                try {
                                    // 删除成功, 删本地，删云，并跳转到上一个页面
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (videoFile != null && videoFile.exists()) {
                                                videoFile.delete();
                                            }
                                        }
                                    }).start();

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                goBack();
                            } else {
                                WpkToastUtil.showText(getString(R.string.failed));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            WpkToastUtil.showText(getString(R.string.failed));
                        }
                    }
                });
                tbwhd.dismiss();
            }

            @Override
            public void doCancel() {
                tbwhd.dismiss();
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return goBack();
        }
        return false;
    }

    //返回
    private boolean goBack() {
        if (isFullScreen) {
            setScreen(false);
            return false;
        }
        try {
            if (mOrientationListener != null) {
                mOrientationListener.disable();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "goBack: " + e.getMessage());
        }
        if (mVideoMode == VIDEO_COMMON) {
            if (AlarmVideoProgress.isDownload) {
                AlarmVideoProgress.stopDownloadVideo = true;
            }
        }
        AnimLoading.cancel();
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(ALARMLIST, recordList);
        intent.putExtra(CMC_IS_LIVE, mRecord.getIsLive() == 1);
        getActivity().setResult(RESULT_OK, intent);
        finish();
        return true;
    }

    //加载UI
    private void initUI() {
        dbPhotoLiveView = findViewById(R.id.live_view);
        dbPhotoLiveView.setFull(false);
        tv_video_time = findViewById(R.id.tv_video_time);
        tv_startTime = (TextView) findViewById(R.id.tv_alarm_startTime);
        tv_alarm_startTime_land = (TextView) findViewById(R.id.tv_alarm_startTime_land);
        iv_play_icon = (ImageView) findViewById(R.id.iv_alarm_play_icon);
        iv_full_screen = (ImageView) findViewById(R.id.iv_full_screen);
        frameLayout = (FrameLayout) findViewById(R.id.fl_video);
        frameLayout.setMinimumHeight(CommonMethod.getHasVirtualKeyWidth(this) / 16 * 9);
        seekBar = (SeekBar) findViewById(R.id.sb_alarm_seekbar);
        sb_alarm_seekbar_land = (SeekBar) findViewById(R.id.sb_alarm_seekbar_land);
        rl_sound = (RelativeLayout) findViewById(R.id.rl_alarm_player_sound);
        rl_alarm_player_delete = (RelativeLayout) findViewById(R.id.rl_alarm_player_delete);
        rl_content = findViewById(R.id.rl_content);
        iv_sound = (ImageView) findViewById(R.id.iv_alarm_sound);
        iv_share = (ImageView) findViewById(R.id.iv_alarm_share);
        iv_alarm_download = (ImageView) findViewById(R.id.iv_alarm_download);
        iv_delete = (ImageView) findViewById(R.id.iv_alarm_delete);
        iv_fillscreen_land = (ImageView) findViewById(R.id.iv_fillscreen_land);
        rl_control_bar = (RelativeLayout) findViewById(R.id.rl_control_bar);
        rl_live_stream = (RelativeLayout) findViewById(R.id.rl_live_stream);
        rl_jump_to_play_back = (RelativeLayout) findViewById(R.id.rl_jump_to_play_back);
        iv_alarm_playback_land = (ImageView) findViewById(R.id.iv_alarm_playback_land);
        iv_back_land = (ImageView) findViewById(R.id.iv_back_land);
        iv_alarm_living_land = (ImageView) findViewById(R.id.iv_alarm_living_land);
        ll_video_player_bottom_bar = (LinearLayout) findViewById(R.id.ll_video_player_bottom_bar);
        ll_right_land = (LinearLayout) findViewById(R.id.ll_right_land);
        mLandSeekRl = (RelativeLayout) findViewById(R.id.seek_bar_land);
        rl_player_zone = (RelativeLayout) findViewById(R.id.rl_player_zone);
        rl_operator = (RelativeLayout) findViewById(R.id.rl_operator);
        rl_title_bar = (FrameLayout) findViewById(R.id.title_bar);
        tv_startTime.setText(getString(R.string.wyze_kvs_player_default_time));
        tv_alarm_startTime_land.setText(getString(R.string.wyze_kvs_player_default_time));
        iv_default_bg = (ImageView) findViewById(R.id.iv_default_bg);
        tv_improve_share = (TextView) findViewById(R.id.wyze_event_improve_the_video);
        tv_improve_text = (TextView) findViewById(R.id.wyze_event_improve_text);
        tv_improve_layout = (RelativeLayout) findViewById(R.id.wyze_event_improve_the_relativelayout);
        tv_improve_thanks = (RelativeLayout) findViewById(R.id.wyze_event_improve_the_thanks);
        tv_title = findViewById(R.id.tv_title);

        mLandTitleBar = findViewById(R.id.replay_tittle_bar_land);//全屏标题bar
        mLandDeviceTv = findViewById(R.id.replay_tittle_record_time_land_left);//全屏设备名称
        mLandInfoTv = findViewById(R.id.replay_tittle_record_time_land_right);//全屏信息

        //下载
        mShareDownloadRpb = findViewById(R.id.event_share_download_rpb);
        download_rl_loading = findViewById(R.id.wyze_share_rl_loading);
        download_rl_loading.setVisibility(View.GONE);
        //加载动画
        rl_loading = findViewById(R.id.rl_loading);
        //viewpager
        viewpager = findViewById(R.id.viewpager);
        //本地保存
        sharedPreferences = getActivity().getSharedPreferences("WYZE_USER", Activity.MODE_PRIVATE);
        spEdit = sharedPreferences.edit();
    }

    //滑动播放是否继续
    private void continuePlay() {
        if (isPause) {
            if (mPlayer != null) {
                mPlayer.start();
                resumeSound();
                isPause = false;
                runProgUpdater("continuePlay");
            }
        } else {
            playerHandler.sendEmptyMessage(MSG_START_PLAY);
        }
        hidePlayIcon();
        iv_play_icon.setSelected(false);
    }

    //暂停播放
    private void pausePlay() {
        clearKeepScreenOn();
        if (mVideoMode == VIDEO_COMMON) {
            if (mPlayer != null && mPlayer.isPlaying()) {
                mPlayer.pause();
                isPause = true;
                pauseSound();
                uiForPlayStop();
            }
        } else {
            DashDecodeController.instance(mMac).pauseDashCallBack();
//            DashDecodeController.instance(mMac).setIsParseVideo(false);
            DashManager.instance().pausePlaying();
        }
    }


    private PointF first_1 = new PointF();
    private PointF first_2 = new PointF();
    private boolean AREA = false;
    private final int DOUBLETIME = 500;//ms
    private final int DOUBLEAREA = 30;//dp

    private void initViewPager() {
        //初始化数据
        if (!isFromPush) {
            currentIndex = getIntent().getIntExtra(CURRENTPOSITION, 0);
            ArrayList<EventItem> alarmlist = getIntent().getParcelableArrayListExtra(ALARMLIST);
            if (alarmlist != null) {
                recordList.addAll(alarmlist);
            }
            mMac = alarmlist.get(getIntent().getIntExtra(CURRENTPOSITION, 0)).getDeviceMac();
            C.currentCamMac = mMac;

            mTag = getIntent().getStringExtra(EVENTREQUESTTAG);
            loadTime = getIntent().getLongExtra(EVENTREQUESTSTARTTIME, 0);

            mRecord = recordList.get(currentIndex);
        } else {
            mMac = mRecord.getDeviceMac();
            C.currentCamMac = mMac;
            Log.i(TAG, "get notification info,mac is " + mMac);
        }

        getDeviceInfo();
        getSdCardInfo();
        if (mRecord.getEvent_value().equals("13")) {
            DashDecodeController.instance(mMac);
            showVideoInfo();

            isLive = mRecord.getIsLive();
            if (isLive == 0) {
                //回放
                mVideoMode = VIDEO_DASH_PLAYBACK;
                iv_share.setVisibility(View.VISIBLE);
                iv_alarm_download.setVisibility(View.VISIBLE);
            } else {
                //直播
                mVideoMode = VIDEO_DASH_LIVING;
                iv_share.setVisibility(View.GONE);
                iv_alarm_download.setVisibility(View.GONE);
                seekBar.setProgress(seekBar.getMax());
                sb_alarm_seekbar_land.setProgress(seekBar.getMax());
            }
            if (isFromPush) {
                DashDecodeController.instance(mMac).setUiHandler(playerHandler);
                DashDecodeController.instance(mMac).setDeviceModel(deviceModel);
                setDashMode(mVideoMode, false);
            }
            initBroadcast();
            String text = (getResources().getString(R.string.wyze_events_video_ai_share)).concat(" ").concat(getResources().getString(R.string.wyze_event_improve_share_video));
            tv_improve_text.setText(text);
        } else {
            mVideoMode = VIDEO_COMMON;
            iv_share.setVisibility(View.VISIBLE);
            iv_alarm_download.setVisibility(View.VISIBLE);
            uiWriteCopywriter();
            String text = getResources().getString(R.string.wyze_event_improve_share_video);
            tv_improve_text.setText(text);
        }
        Log.e(TAG, "picture url is: ");
        Glide.with(getActivity())
                .load(mRecord.getPicUrl())
                .placeholder(R.drawable.alarmvideo_bg)
                .error(R.drawable.alarmvideo_bg)
                .into(iv_default_bg);

        fragments = new ArrayList<>();
        if (recordList != null && recordList.size() >= 1) {
            for (int i = 0; i < recordList.size(); i++) {
                FragmentVideoPlayer fragmentVideoPlayer = FragmentVideoPlayer.newInstance(recordList.size(), i);
                fragments.add(fragmentVideoPlayer);
            }
        }
        titleAdapter = new MyFragmentAdapter(DBKvsEventPlayerActivity.this,
                getSupportFragmentManager(), fragments);
        viewpager.setAdapter(titleAdapter);
        viewpager.setCurrentItem(currentIndex, true);
        viewpager.postDelayed(new Runnable() {
            @Override
            public void run() {
                isCanLoadMore = true;
            }
        }, 2000);

        viewpager.setOnTouchListener(new View.OnTouchListener() {
            PointF startPoint = new PointF(); // 用于记录开始时候的坐标位置
            float distance = 0;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getActionMasked()) {
                    case MotionEvent.ACTION_DOWN: {
                        isPageWillScroll = true;
                        MODE = MODE_DRAG;
                        startPoint.set(event.getX(), event.getY());
//                        setControllBar();
                        if (!AREA) {
                            first_1.set(event.getX(), event.getY());
                            AREA = true;
                        } else {
                            first_2.set(event.getX(), event.getY());
                            AREA = false;
                        }
                    }
                    break;
                    case MotionEvent.ACTION_MOVE: {
                        if (MODE == MODE_DRAG) {
                            if (isZoom) {
                                dragView(event);
                                return true;
                            }
                        } else if (MODE == MODE_SCALE) {
                            setZoom(event);
                            return true;
                        }
                    }
                    break;
                    case MotionEvent.ACTION_UP: {
                        isPageWillScroll = false;
                        doubleClick(event);
                    }
                    break;
                    case MotionEvent.ACTION_POINTER_DOWN: {
                        MODE = MODE_SCALE;
                        distance = distance(event);
                    }
                    break;
                }
                return false;
            }

            private void setControllBar() {
                if (!isFullScreen) {
                    if (isDouble) {
                        if (rl_control_bar.isShown()) {
                            rl_control_bar.setVisibility(View.GONE);
                        } else {
                            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                            rl_control_bar.setLayoutParams(layoutParams);
                            rl_control_bar.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }

            private void dragView(MotionEvent event) {
                // 处理图片拖动
                float dx = event.getX() - startPoint.x; // 得到x轴的移动距离
                float dy = event.getY() - startPoint.y; // 得到y轴的移动距离
                if (Math.sqrt(dx * dx + dy * dy) > 10f) { //避免和双击冲突,大于50f才算是拖动
                    startPoint.set(event.getX(), event.getY());
                    /**
                     * 计算屏幕剩余大小
                     */


                    float translationX = 0, translationY = 0;

                    if (mVideoMode == VIDEO_COMMON) {
                        translationX = sfv_videoplay.getTranslationX();
                        translationY = sfv_videoplay.getTranslationY();
                    } else {
                        translationX = iv_video_display.getTranslationX();
                        translationY = iv_video_display.getTranslationY();
                    }
                    if (dx > 0) {
                        //向右滑动
                        if (translationX + dx <= 0) {

                            if (mVideoMode == VIDEO_COMMON) {
                                sfv_videoplay.setTranslationX(translationX + dx);
                            } else {
                                iv_video_display.setTranslationX(translationX + dx);
                            }
//                            Log.e(TAG, "translationX:" + translationX + ",dx:" + dx);
                        } else {
//                            Log.e(TAG, "translationX:" + translationX + ",dx:" + dx + ",total:" + translationX + dx);
                        }
                    } else {
                        if (isFullScreen) {
                            //向左滑动
                            if (Math.abs(translationX + dx) <= (scaleWidth - screenWidth)) {

//                                Log.e(TAG, "translationX:" + translationX + ",dx:" + dx);
                                if (mVideoMode == VIDEO_COMMON) {
                                    sfv_videoplay.setTranslationX(translationX + dx);
                                } else {
                                    iv_video_display.setTranslationX(translationX + dx);
                                }
                            }
                        } else {
                            //向左滑动
                            if (Math.abs(translationX + dx) <= (scaleWidth - screenWidth)) {

//                                Log.e(TAG, "translationX:" + translationX + ",dx:" + dx);
                                if (mVideoMode == VIDEO_COMMON) {
                                    sfv_videoplay.setTranslationX(translationX + dx);
                                } else {
                                    iv_video_display.setTranslationX(translationX + dx);
                                }
                            }
                        }
                    }

                    if (dy > 0) {
                        //向下滑动
                        if (translationY + dy <= 0) {

                            if (mVideoMode == VIDEO_COMMON) {
                                sfv_videoplay.setTranslationY(translationY + dy);
                            } else {
                                iv_video_display.setTranslationY(translationY + dy);
                            }
                        }
                    } else {
                        if (isFullScreen) {
                            if (Math.abs(translationY + dy) <= scaleHeight - screenHeight) {

                                if (mVideoMode == VIDEO_COMMON) {
                                    sfv_videoplay.setTranslationY(translationY + dy);
                                } else {
                                    iv_video_display.setTranslationY(translationY + dy);
                                }
                            }
                        } else {
                            if (isDouble) {
                                float showAreaHeight = screenHeight;
                                //向上滑动
                                if (Math.abs(translationY + dy) <= scaleHeight - showAreaHeight) {

                                    if (mVideoMode == VIDEO_COMMON) {
                                        sfv_videoplay.setTranslationY(translationY + dy);
                                    } else {
                                        iv_video_display.setTranslationY(translationY + dy);
                                    }
                                }
                            } else {
                                float showAreaHeight = CommonMethod.getVideoViewVerticalHeight(new WeakReference<Activity>(DBKvsEventPlayerActivity.this));
                                //向上滑动
                                if (Math.abs(translationY + dy) <= scaleHeight - showAreaHeight) {
                                    if (mVideoMode == VIDEO_COMMON) {
                                        sfv_videoplay.setTranslationY(translationY + dy);
                                    } else {
                                        iv_video_display.setTranslationY(translationY + dy);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            /**
             * 计算两个手指间的距离
             *
             * @param event
             * @return
             */
            private float distance(MotionEvent event) {
                float dx = event.getX(1) - event.getX(0);
                float dy = event.getY(1) - event.getY(0);
                // 使用勾股定理返回两点之间的距离
                return (float) Math.sqrt(dx * dx + dy * dy);
            }

            private void setZoom(MotionEvent event) {
                if (mVideoMode == VIDEO_COMMON) {
                    if (sfv_videoplay == null) return;
                } else {
                    if (iv_video_display == null) {
                        return;
                    }
                }
                if (event.getPointerCount() != 2) return;
                float endDistance = distance(event);
                if (endDistance > 10f) { // 两个手指并拢在一起的时候像素大于10
                    float scale = (endDistance / distance);// 得到缩放倍数
                    if (scale > 1) {
                        //放大
                        int width = 0, height = 0;
                        if (mVideoMode == VIDEO_COMMON) {
                            width = (int) (sfv_videoplay.getWidth() * scale);
                            height = (int) (sfv_videoplay.getHeight() * scale);
                        } else {
                            width = (int) (iv_video_display.getWidth() * scale);
                            height = (int) (iv_video_display.getHeight() * scale);
                        }
                        if (width <= screenWidth * scaleMaxValue) {
                            distance = endDistance;//重置距离
                            if (mVideoMode == VIDEO_COMMON) {
                                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(width, height);
                                sfv_videoplay.setLayoutParams(surface_params);
                            } else {
                                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(width, height);
                                iv_video_display.setLayoutParams(surface_params);
                            }
                            JustifyTran();
                            scaleWidth = width;
                            scaleHeight = height;
                            isZoom = true;
                        }
                    } else if (scale < 1) {
                        //缩小
                        int width = 0, height = 0;
                        if (mVideoMode == VIDEO_COMMON) {
                            width = (int) (sfv_videoplay.getWidth() * scale);
                            height = (int) (sfv_videoplay.getHeight() * scale);
                        } else {
                            width = (int) (iv_video_display.getWidth() * scale);
                            height = (int) (iv_video_display.getHeight() * scale);
                        }
                        int clickedWidth = 0;
                        if (isDouble) {
                            clickedWidth = screenWidth;
                        } else {
                            clickedWidth = screenWidth;
                        }
                        if (width >= clickedWidth) {
                            distance = endDistance;//重置距离
                            if (mVideoMode == VIDEO_COMMON) {
                                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(width, height);
                                sfv_videoplay.setLayoutParams(surface_params);
                                sfv_videoplay.setTranslationX(0);
                                sfv_videoplay.setTranslationY(0);
                            } else {
                                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(width, height);
                                iv_video_display.setLayoutParams(surface_params);
                                iv_video_display.setTranslationX(0);
                                iv_video_display.setTranslationY(0);
                            }
                            JustifyTran();
                            scaleWidth = width;
                            scaleHeight = height;
                            isZoom = true;
                        } else {
                            restoreShowArea();
                        }
                    }

                }

            }


            /**
             * 中心点放大
             */
            private void JustifyTran() {
                int mSurfaceViewWidth = 0, mSurfaceViewHeight = 0;
                if (mVideoMode == VIDEO_COMMON) {
                    mSurfaceViewWidth = sfv_videoplay.getWidth();
                    mSurfaceViewHeight = sfv_videoplay.getHeight();
                } else {
                    mSurfaceViewWidth = iv_video_display.getWidth();
                    mSurfaceViewHeight = iv_video_display.getHeight();
                }
//                Log.i(TAG, "JustifyTran mSurfaceViewWidth = " + mSurfaceViewWidth + "  mSurfaceViewHeight = " + mSurfaceViewHeight);

                int hasVirtualKeyWidth = screenWidth;
                int hasVirtualKeyHeight = screenHeight;
//                Log.i(TAG, "JustifyTran hasVirtualKeyWidth = " + hasVirtualKeyWidth + "  hasVirtualKeyHeight = " + hasVirtualKeyHeight);

                int tranx = 0, trany = 0;
                int x2 = mSurfaceViewWidth / 2 - hasVirtualKeyWidth / 2;
                int y2 = mSurfaceViewHeight / 2 - hasVirtualKeyHeight / 2;
                tranx = -x2;
                trany = -y2;
                if (mVideoMode == VIDEO_COMMON) {
                    sfv_videoplay.setTranslationX(tranx);
                    sfv_videoplay.setTranslationY(trany);
                } else {
                    iv_video_display.setTranslationX(tranx);
                    iv_video_display.setTranslationY(trany);
                }
            }

        });
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //停止下载
                if (AlarmVideoProgress.isDownload) {
                    AlarmVideoProgress.stopDownloadVideo = true;
                }
                hidePlayIcon();
                if (isPageWillScroll) {
                    pausePlay();
                    isPageWillScroll = false;
                }
                if (positionOffset > currentPosition) {//滑动中 向左向右滑动 将老的界面的默认图显示出来

                    //右滑
                    currentPosition = positionOffset;
                    if (currentIndex != (recordList.size() - 1)) {
                        fragments.get(currentIndex).showBgPic(true);
                        uiForAiHintVisible(false);
                    }
                    hasSwipedViewPager = true;
                    WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_FIREBASE, 1,
                            StatIndex.WYZE_CAM_EVENT_SWIPE_RIGHT);
                } else if (positionOffset < currentPosition) {
                    //左滑
                    currentPosition = positionOffset;
                    if (currentIndex != 0) {
                        fragments.get(currentIndex).showBgPic(true);
                        uiForAiHintVisible(false);
                    }
                    hasSwipedViewPager = true;
                    WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_FIREBASE, 1,
                            StatIndex.WYZE_CAM_EVENT_SWIPE_LEFT);
                } else if (currentIndex == (recordList.size() - 1) && positionOffset == currentPosition) {
//                    Log.i(TAG, "onPageScrolled  position = " + position + "  positionOffset = " + positionOffset + "    positionOffsetPixels =  " + positionOffsetPixels);
                    //不能加载的情况：不可加载，时间太短，推送
                    if (!isCanLoadMore || Math.abs(lastLoadTime - System.currentTimeMillis()) <= 2000 || isFromPush) {
                        return;
                    }

                    if (currentIndex != 0) {
                        fragments.get(currentIndex).showBgPic(true);
                        uiForAiHintVisible(false);
                    }
                    hasSwipedViewPager = true;
                    //加载更多
                    loadMore();
                }



            }

            @Override
            public void onPageSelected(int position) {//滑动之后的界面 刷新数据，将新的界面的默认图消失并播放新视频
                statisticDuration();//切换 打点
                currentIndex = position;
                isCurrentPage = false;
                isPlayOver = false;
                mRecord = recordList.get(currentIndex);
                mMac = mRecord.getDeviceMac();
                C.currentCamMac = mMac;
                deviceModel = mRecord.getEventModel();

                getDeviceInfo();
                Glide.with(getActivity())
                        .load(mRecord.getPicUrl())
                        .placeholder(R.drawable.alarmvideo_bg)
                        .error(R.drawable.alarmvideo_bg)
                        .into(iv_default_bg);
                iv_default_bg.setVisibility(View.VISIBLE);

                seekBar.setProgress(0);
                sb_alarm_seekbar_land.setProgress(0);
                tv_startTime.setText(getString(R.string.wyze_kvs_player_default_time));
                tv_alarm_startTime_land.setText(getString(R.string.wyze_kvs_player_default_time));

                Log.e(TAG, "onPageSelected, record: startTime:" + mRecord.getStart_time() + ",endTime:" + mRecord.getEnd_time()+"。。。"+mRecord.getEvent_value());
                if (mRecord.getEvent_value().equals("13")) {
                    DashDecodeController.instance(mMac).setUiHandler(playerHandler);
                    DashDecodeController.instance(mMac).setDeviceModel(deviceModel);
                    showVideoInfo();
                    isLive = mRecord.getIsLive();
                    if (isLive == 0) {
                        //回放
                        mVideoMode = VIDEO_DASH_PLAYBACK;
                        iv_share.setVisibility(View.VISIBLE);
                        iv_alarm_download.setVisibility(View.VISIBLE);
                    } else {
                        //直播
                        mVideoMode = VIDEO_DASH_LIVING;
                        iv_share.setVisibility(View.GONE);
                        iv_alarm_download.setVisibility(View.GONE);
                        seekBar.setProgress(seekBar.getMax());
                        sb_alarm_seekbar_land.setProgress(seekBar.getMax());
                    }
                    setDashMode(mVideoMode, false);
                    String text = (getResources().getString(R.string.wyze_events_video_ai_share)).concat(" ").concat(getResources().getString(R.string.wyze_event_improve_share_video));
                    tv_improve_text.setText(text);
                } else {
                    if (mVideoMode == VIDEO_DASH_LIVING || mVideoMode == VIDEO_DASH_PLAYBACK) {
                        clear();
                    }
                    mVideoMode = VIDEO_COMMON;
                    showVideoInfo();
                    iv_share.setVisibility(View.VISIBLE);
                    iv_alarm_download.setVisibility(View.VISIBLE);
                    if (AlarmVideoProgress.isDownload) {
                        AlarmVideoProgress.stopDownloadVideo = true;
                    }
                    stopOldVideo();
                    setVideoData("viewpager select");
                    uiWriteCopywriter();
                    String text = getResources().getString(R.string.wyze_event_improve_share_video);
                    tv_improve_text.setText(text);

                    tv_startTime.setTextColor(Color.parseColor("#FF7E8D92"));
                    tv_startTime.setBackground(null);
                    tv_alarm_startTime_land.setTextColor(Color.parseColor("#FF7E8D92"));
                    tv_alarm_startTime_land.setBackground(null);
                }

                hasSwipedViewPager = false;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == 0) {//滑动停止
                    fragments.get(viewpager.getCurrentItem()).showBgPic(false);
                    uiForAiHintVisible(true);
                    if (isCurrentPage) {//页面未变化，继续播放
                        if (isPlayOver) {
                            uiForRePlayStop();
                        }
                        if (mVideoMode == VIDEO_COMMON) {
                            if (!isPlayOver) {
                                continuePlay();
                            }
                        } else {
                            if (mVideoMode == VIDEO_DASH_LIVING) {
                                //Live
                                long tsInMs = DashManager.instance().prog2TsInMs(isFullScreen ? sb_alarm_seekbar_land.getProgress() : seekBar.getProgress(), isFullScreen ? sb_alarm_seekbar_land.getMax() : seekBar.getMax());
                                DashDecodeController.instance(mMac).resumeDashCallBack();
                                DashManager.instance().resumePlaying(tsInMs);
                            }
                            if (mVideoMode == VIDEO_DASH_PLAYBACK) {
                                //playback
                                resumePlay();
                            }
                        }
                    }
                    isCurrentPage = true;
                }
                setScreen(isFullScreen);
            }
        });
    }

    private void showVideoInfo() {
        tv_video_time.setVisibility(isFullScreen ? View.GONE : View.VISIBLE);
        if (mRecord.getRead_state() == 0) {
            sendSetRead();
        }
        String timeText = (mRecord.isPerson() ? getString(R.string.wyze_person) : mRecord.getEventAlarmValue(getActivity()))
                + " at " + CommonMethod.getSystemTime(mRecord.getEvent_ts(), getActivity());
        tv_video_time.setText(timeText);
        mLandInfoTv.setText(timeText);

        DeviceModel.Data.DeviceData device = WpkDeviceManager.getInstance().getDeviceModelById(mRecord.getDeviceMac());
        String devicename = device != null ? device.getNickname() : mRecord.getDeviceMac();
        mLandDeviceTv.setText(devicename);
        tv_title.setText(devicename);
    }

    private void initBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mReceiver, filter);
    }

    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG, "BroadcastReceiver  action = " + action);
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String key = intent.getStringExtra("reason");
                if (key.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                    if (!isChangePage) {
                        isChangePage = true;
                        Log.i(TAG, "press Home key");
                    }
                }
            }

            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                Log.i(TAG, "press screen off");
                if (!isChangePage) {
                    isChangePage = true;
                }
            }
        }
    };


    long[] mHits = new long[2];

    //双击
    private void doubleClick(MotionEvent event) {
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        //双击事件的时间间隔500ms
        if (DOUBLETIME > (SystemClock.uptimeMillis() - mHits[0])) {
            int xDiff;
            int yDiff;
            if (!AREA) {
                xDiff = (int) Math.abs(event.getX() - first_1.x);
                yDiff = (int) Math.abs(event.getY() - first_1.y);
            } else {
                xDiff = (int) Math.abs(event.getX() - first_2.x);
                yDiff = (int) Math.abs(event.getY() - first_2.y);
            }
            if (xDiff < DOUBLEAREA && yDiff < DOUBLEAREA) {
                //双击后具体的操作
                if (isZoom) {
                    //恢复原来的大小和位置
                    restoreShowArea();
                    MODE = 0;
                } else {
                    //放大
                    scaleShowArea(event);
                    MODE = MODE_SCALE;
                }
            }
        } else {
            //单击双屏时显示bar
            if (MODE == MODE_SCALE) {
                return;
            }

            if (isPlayOver) {
                return;
            }
            if (isFullScreen) {
                if (mLandSeekRl.getVisibility() == View.VISIBLE || mLandTitleBar.getVisibility() == View.VISIBLE) {
                    hidePlayIcon();
                } else {
                    if (playerHandler.hasMessages(MSG_HIDE_LAND_BAR)) {
                        playerHandler.removeMessages(MSG_HIDE_LAND_BAR);
                    }
                    mLandTitleBar.setVisibility(View.VISIBLE);
                    mLandSeekRl.setVisibility(View.VISIBLE);
                    ll_right_land.setVisibility(View.VISIBLE);
                    iv_play_icon.setVisibility(View.VISIBLE);

                    mLandTitleBar.bringToFront();
                    mLandSeekRl.bringToFront();
                    ll_right_land.bringToFront();
                    iv_play_icon.bringToFront();
                    playerHandler.sendEmptyMessageDelayed(MSG_HIDE_LAND_BAR, 3000);
                }
            } else {
                if (iv_play_icon.isShown()) {
                    hidePlayIcon();
                } else {
                    if (playerHandler.hasMessages(MSG_HIDE_PORTRAIT_PLAY_ICON)) {
                        playerHandler.removeMessages(MSG_HIDE_PORTRAIT_PLAY_ICON);
                    }
                    iv_play_icon.setVisibility(View.VISIBLE);
                    iv_play_icon.bringToFront();
                    rl_operator.setVisibility(View.VISIBLE);
                    rl_operator.bringToFront();
                    playerHandler.sendEmptyMessageDelayed(MSG_HIDE_PORTRAIT_PLAY_ICON, 3000);
                }
            }
        }

    }

    /**
     * 双击恢复
     */
    private void restoreShowArea() {
        if (mVideoMode == VIDEO_COMMON) {
            if (sfv_videoplay == null) {
                return;
            }
        } else {
            if(isDBModel()){

            }else{
                if (iv_video_display == null) {
                    return;
                }
            }

        }
        isDouble = false;
        if (isFullScreen) {
            RelativeLayout.LayoutParams rl_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            rl_player_zone.setLayoutParams(rl_params);

            frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));

            rl_control_bar.setVisibility(View.GONE);


            Log.i(TAG, "restoreShowArea :"+mVideoMode);
            if (mVideoMode == VIDEO_COMMON) {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                sfv_videoplay.setLayoutParams(layoutParams);
                sfv_videoplay.setTranslationX(0);
                sfv_videoplay.setTranslationY(0);
            } else {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

                if(isDBModel()){


                }else{
                    iv_video_display.setLayoutParams(layoutParams);
                    iv_video_display.setTranslationX(0);
                    iv_video_display.setTranslationY(0);
                }

            }
        } else {

            RelativeLayout.LayoutParams rl_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            rl_params.addRule(RelativeLayout.BELOW, R.id.tv_video_time);
            rl_player_zone.setLayoutParams(rl_params);

            RelativeLayout.LayoutParams control_bar_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            control_bar_params.addRule(RelativeLayout.BELOW, R.id.fl_video);
            rl_control_bar.setLayoutParams(control_bar_params);

            if(isDBModel()){
                int mWidthPixels = CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this));
                int height = (int) (4 * mWidthPixels / 3.0f);
                frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(mWidthPixels, height));
            }else{
                frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, frameLayout.getMinimumHeight()));
            }



            tv_video_time.bringToFront();
            rl_title_bar.bringToFront();
            screenWidth = CommonMethod.getHasVirtualKeyWidth(getActivity());
            screenHeight = isFullScreen ? CommonMethod.getHasVirtualKeyHeight(getActivity()) : screenWidth * 9 / 16;

            if (mVideoMode == VIDEO_COMMON) {

                if(isDBModel()){

                    int mWidthPixels = CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this));
                    int height = (int) (4 * mWidthPixels / 3.0f);
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(mWidthPixels, height);
                    sfv_videoplay.setLayoutParams(layoutParams);
                    sfv_videoplay.setTranslationX(0);
                    sfv_videoplay.setTranslationY(0);

                }else{
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(screenWidth, screenHeight);
                    sfv_videoplay.setLayoutParams(layoutParams);
                    sfv_videoplay.setTranslationX(0);
                    sfv_videoplay.setTranslationY(0);


                }

            } else {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this)), CommonMethod.getVideoViewVerticalHeight(new WeakReference<Activity>(this)));
                if(isDBModel()){

                }else{
                    iv_video_display.setLayoutParams(layoutParams);
                    iv_video_display.setTranslationX(0);
                    iv_video_display.setTranslationY(0);
                }
            }

        }
        isZoom = false;
    }

    /**
     * 双击放大
     *
     * @param event 事件
     */
    private void scaleShowArea(MotionEvent event) {
        if (mVideoMode == VIDEO_COMMON) {
            if (sfv_videoplay == null) {
                return;
            }
        } else {
            if (iv_video_display == null) {
                return;
            }
        }

        isDouble = true;

        /*
         * 计算屏幕剩余大小
         */

        float centerX;
        float centerY;
        float translationX = 0f;
        float translationY = 0f;
        float scale4X = event.getX() * scaleMaxValue;
        float scale4Y = event.getY() * scaleMaxValue;

        if (isFullScreen) {
            centerX = (float) (screenWidth / 2.0);
            centerY = (float) (screenHeight / 2.0);
            if (mVideoMode == VIDEO_COMMON) {
                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(sfv_videoplay.getWidth() * scaleMaxValue, sfv_videoplay.getHeight() * scaleMaxValue);
                sfv_videoplay.setLayoutParams(surface_params);
                scaleWidth = surface_params.width;
                scaleHeight = surface_params.height;
            } else {
                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(iv_video_display.getWidth() * scaleMaxValue, iv_video_display.getHeight() * scaleMaxValue);
                iv_video_display.setLayoutParams(surface_params);
                scaleWidth = surface_params.width;
                scaleHeight = surface_params.height;
            }

        } else {
            centerX = (float) (screenWidth / 2.0);
//            centerY = (float) ((screenHeight - rl_title_bar.getHeight() - ll_video_player_bottom_bar.getHeight()) / 2.0);
            centerY = (float) (screenHeight / 2.0);

            RelativeLayout.LayoutParams rl_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            rl_params.addRule(RelativeLayout.BELOW, R.id.tv_video_time);
            rl_player_zone.setLayoutParams(rl_params);

            RelativeLayout.LayoutParams control_bar_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            control_bar_params.addRule(RelativeLayout.BELOW, R.id.fl_video);
            rl_control_bar.setLayoutParams(control_bar_params);

            frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, frameLayout.getMinimumHeight()));
            if (mVideoMode == VIDEO_COMMON) {
                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(sfv_videoplay.getWidth() * scaleMaxValue, sfv_videoplay.getHeight() * scaleMaxValue);
                sfv_videoplay.setLayoutParams(surface_params);
                scaleWidth = surface_params.width;
                scaleHeight = surface_params.height;
            } else {
                FrameLayout.LayoutParams surface_params = new FrameLayout.LayoutParams(iv_video_display.getWidth() * scaleMaxValue, iv_video_display.getHeight() * scaleMaxValue);
                iv_video_display.setLayoutParams(surface_params);
                scaleWidth = surface_params.width;
                scaleHeight = surface_params.height;
            }
            tv_video_time.bringToFront();
            rl_title_bar.bringToFront();


        }

        if (scale4X < centerX && scale4Y < centerY) {
            //不移动，直接放大
            Log.e(TAG, "左上角,直接放大");
        } else if (scale4X > centerX && scale4Y > centerY) {
            translationX = centerX - scale4X;
            translationY = centerY - scale4Y;

            if ((scaleWidth - scale4X) < centerX) {
                translationX += (centerX - (scaleWidth - scale4X));
            }

            if ((scaleHeight - scale4Y) < centerY) {
                translationY += (centerY - (scaleHeight - scale4Y));
            }
            if (mVideoMode == VIDEO_COMMON) {
                 sfv_videoplay.setTranslationX(translationX);
                sfv_videoplay.setTranslationY(translationY);
            } else {
                iv_video_display.setTranslationX(translationX);
                iv_video_display.setTranslationY(translationY);
            }
            Log.e(TAG, "右下角,translationX:" + translationX + " translationY:" + translationY);
        } else if (scale4X > centerX && scale4Y < centerY) {
            translationX = centerX - scale4X;
            if ((scaleWidth - scale4X) < centerX) {
                translationX += (centerX - (scaleWidth - scale4X));
            }
            if (mVideoMode == VIDEO_COMMON) {
                sfv_videoplay.setTranslationX(translationX);
                sfv_videoplay.setTranslationY(translationY);
            } else {
                iv_video_display.setTranslationX(translationX);
                iv_video_display.setTranslationY(translationY);
            }
            Log.e(TAG, "右上角,translationX:" + translationX + " translationY:" + translationY);
        } else {
            translationY = centerY - scale4Y;
            if ((scaleHeight - scale4Y) < centerY) {
                translationY += (centerY - (scaleHeight - scale4Y));
            }
            if (mVideoMode == VIDEO_COMMON) {
                sfv_videoplay.setTranslationX(translationX);
                sfv_videoplay.setTranslationY(translationY);
            } else {
                iv_video_display.setTranslationX(translationX);
                iv_video_display.setTranslationY(translationY);
            }
            Log.e(TAG, "左下角,translationX:" + translationX + " translationY:" + translationY);
        }
        isZoom = true;
    }

    //暂停播放
    private void stopOldVideo() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        if (playAudioThread != null) {
            playAudioThread.setPause(true);
        }
        try {
            sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            if (mPCMAudioTrack != null) {
                mPCMAudioTrack.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        clearSeekbarUpdater();
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
//        mRecord = null;
        if (sfv_videoplay != null) {
            sfv_videoplay = null;
        }
    }

    //横竖屏切换
    private void setScreen(boolean mIsFullScreen) {
        if (mIsFullScreen) {
            isFullScreen = true;
            if (isReverseLand) {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            } else {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            }
            isZoom = false;
            isReverseLand = false;
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            rl_operator.setVisibility(View.GONE);
        } else {
            isDouble = false;
            isZoom = false;
            isFullScreen = false;
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            rl_operator.setVisibility(View.VISIBLE);
            rl_operator.bringToFront();
        }
        setConfigurationChanged();

    }

    /**
     * 系统已经切好横竖屏之后，再去切换UI
     */
    private void setConfigurationChanged() {
        if (isFullScreen) {
            RelativeLayout.LayoutParams videoParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            screenWidth = CommonMethod.getHasVirtualKeyWidth(getActivity());//CommonMethod.getScreenWidth(DBKvsEventPlayerActivity.this);
            screenHeight = isFullScreen ? CommonMethod.getHasVirtualKeyHeight(getActivity()) : screenWidth * 9 / 16;//CommonMethod.getScreenHeight(DBKvsEventPlayerActivity.this);
            if (!isPlayOver) {
                if (playerHandler.hasMessages(MSG_HIDE_LAND_BAR)) {
                    playerHandler.removeMessages(MSG_HIDE_LAND_BAR);
                }
                playerHandler.sendEmptyMessageDelayed(MSG_HIDE_LAND_BAR, 3000);
            }

            rl_player_zone.setLayoutParams(videoParams);

            frameLayout.setLayoutParams(videoParams);

            tv_video_time.setVisibility(View.GONE);
            mLandTitleBar.setVisibility(View.VISIBLE);
            rl_title_bar.setVisibility(View.GONE);
            mLandSeekRl.setVisibility(View.VISIBLE);
            mLandTitleBar.bringToFront();
            mLandSeekRl.bringToFront();
            iv_play_icon.setVisibility(View.VISIBLE);

            iv_play_icon.bringToFront();
            ll_right_land.setVisibility(View.VISIBLE);
            ll_right_land.bringToFront();
            seekBar.setVisibility(View.GONE);
            uiForAiHintVisible(false);
            //播放按钮设置
            RelativeLayout.LayoutParams playericonlayout = new RelativeLayout.LayoutParams(WyzeEventDisplayUtils.dip2px(60), WyzeEventDisplayUtils.dip2px(60));
            playericonlayout.addRule(RelativeLayout.CENTER_IN_PARENT);

            if (iv_play_icon != null) {
                iv_play_icon.setLayoutParams(playericonlayout);
            }

            RelativeLayout.LayoutParams control_bar_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            control_bar_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            control_bar_params.removeRule(RelativeLayout.BELOW);
            rl_control_bar.setLayoutParams(control_bar_params);
            rl_control_bar.setVisibility(View.GONE);
            ll_video_player_bottom_bar.setVisibility(View.GONE);



            if(isDBModel()){
                if(mVideoMode == VIDEO_COMMON){
                    if (sfv_videoplay != null) {
                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                        params.gravity = Gravity.CENTER;
                        sfv_videoplay.setLayoutParams(params);
                        sfv_videoplay.setTranslationX(0);
                        sfv_videoplay.setTranslationY(0);
                    }
                }else{
                    RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) dbPhotoLiveView.getLayoutParams();
                    p.width = RelativeLayout.LayoutParams.MATCH_PARENT;
                    p.height = RelativeLayout.LayoutParams.MATCH_PARENT;
                    dbPhotoLiveView.setLayoutParams(p);
                }

            }else{

                if (iv_video_display != null) {
                    FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                    iv_video_display.setLayoutParams(frameParams);
                    iv_video_display.setTranslationX(0);
                    iv_video_display.setTranslationY(0);
                }

                if (sfv_videoplay != null) {
                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER;
                    sfv_videoplay.setLayoutParams(params);
                    sfv_videoplay.setTranslationX(0);
                    sfv_videoplay.setTranslationY(0);
                }

            }

            RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) iv_default_bg.getLayoutParams();
            p.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            p.height = RelativeLayout.LayoutParams.MATCH_PARENT;
            iv_default_bg.setLayoutParams(p);

        } else {

            screenWidth = CommonMethod.getHasVirtualKeyWidth(getActivity());//CommonMethod.getScreenWidth(DBKvsEventPlayerActivity.this);
            screenHeight = isFullScreen ? CommonMethod.getHasVirtualKeyHeight(getActivity()) : (screenWidth * 9 / 16);//CommonMethod.getScreenHeight(DBKvsEventPlayerActivity.this);
            Log.i(TAG, "portrait screenWidth: " + screenWidth + " ,screenHeight: " + screenHeight);
            if (!isPlayOver) {
                if (playerHandler.hasMessages(MSG_HIDE_PORTRAIT_PLAY_ICON)) {
                    playerHandler.removeMessages(MSG_HIDE_PORTRAIT_PLAY_ICON);
                }
                playerHandler.sendEmptyMessageDelayed(MSG_HIDE_PORTRAIT_PLAY_ICON, 3000);
            }
            rl_title_bar.setVisibility(View.VISIBLE);
            tv_video_time.setVisibility(View.VISIBLE);
            mLandTitleBar.setVisibility(View.GONE);
            mLandSeekRl.setVisibility(View.GONE);
            rl_control_bar.setVisibility(View.VISIBLE);
            seekBar.setVisibility(View.VISIBLE);
            ll_right_land.setVisibility(View.GONE);
            ll_video_player_bottom_bar.setVisibility(View.VISIBLE);

            //播放按钮
            RelativeLayout.LayoutParams playericonlayout = new RelativeLayout.LayoutParams(WyzeEventDisplayUtils.dip2px(60), WyzeEventDisplayUtils.dip2px(60));
            playericonlayout.addRule(RelativeLayout.CENTER_IN_PARENT);
            if (iv_play_icon != null) {
                iv_play_icon.setLayoutParams(playericonlayout);
                iv_play_icon.setVisibility(View.VISIBLE);
                iv_play_icon.bringToFront();
            }

            RelativeLayout.LayoutParams videoParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            videoParams.addRule(RelativeLayout.BELOW, R.id.tv_video_time);
            rl_player_zone.setLayoutParams(videoParams);



            RelativeLayout.LayoutParams control_bar_param = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            control_bar_param.addRule(RelativeLayout.BELOW, R.id.fl_video);
            rl_control_bar.setLayoutParams(control_bar_param);

            RelativeLayout.LayoutParams jump_param = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            jump_param.addRule(RelativeLayout.BELOW, R.id.rl_control_bar);
            jump_param.addRule(RelativeLayout.CENTER_HORIZONTAL);
            rl_control_bar.setVisibility(View.VISIBLE);



            if(isDBModel()){

                int mWidthPixels = CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this));
                int wHeightPixel = (int) (4 * mWidthPixels / 3.0f);

                RelativeLayout.LayoutParams frameParams = new RelativeLayout.LayoutParams(mWidthPixels, wHeightPixel);
                frameLayout.setLayoutParams(frameParams);

                if(mVideoMode == VIDEO_COMMON){// mp4

                    if (sfv_videoplay != null) {
                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(mWidthPixels, wHeightPixel);
                        params.gravity = Gravity.CENTER;
                        sfv_videoplay.setLayoutParams(params);
                        sfv_videoplay.setTranslationX(0);
                        sfv_videoplay.setTranslationY(0);
                    }

                }else{
                    RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) dbPhotoLiveView.getLayoutParams();
                    p.width = mWidthPixels;
                    p.height = wHeightPixel;
                    dbPhotoLiveView.setLayoutParams(p);
                }


                RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) iv_default_bg.getLayoutParams();
                p.width = mWidthPixels;
                p.height = (int) (4 * mWidthPixels / 3.0f);
                iv_default_bg.setLayoutParams(p);


            }else{

                if (sfv_videoplay != null) {
                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(screenWidth, screenHeight);
                    params.gravity = Gravity.CENTER;
                    sfv_videoplay.setLayoutParams(params);
                    sfv_videoplay.setTranslationX(0);
                    sfv_videoplay.setTranslationY(0);
                }


                if (iv_video_display != null) {
                    FrameLayout.LayoutParams switcherImage = new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, CommonMethod.getVideoViewVerticalHeight(new WeakReference<Activity>(this)));
                    iv_video_display.setLayoutParams(switcherImage);
                    iv_video_display.setTranslationX(0);
                    iv_video_display.setTranslationY(0);
                }

                RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) iv_default_bg.getLayoutParams();
                p.width = RelativeLayout.LayoutParams.MATCH_PARENT;
                p.height = CommonMethod.getVideoViewVerticalHeight(new WeakReference<Activity>(this));
                iv_default_bg.setLayoutParams(p);

                RelativeLayout.LayoutParams frameParams = new RelativeLayout.LayoutParams(screenWidth, screenHeight);
                frameLayout.setLayoutParams(frameParams);

            }

            setLayoutPosition();

//            if(sfv_videoplay != null){
//                initSurfaceLayout();
//            }

            scaleHeight = CommonMethod.getVideoViewVerticalHeight(new WeakReference<Activity>(this));

            uiForAiHintVisible(true);
        }

        if (isAudioEnable) {
            iv_sound.setImageResource(R.drawable.ic_sound_full_motion);
        } else {
            iv_sound.setImageResource(R.drawable.ic_sound_mute_full_motion);
        }
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        lastLoadTime = System.currentTimeMillis();
        if (ishasMore) {
            JSONArray mac = null;
            JSONArray tag = null;
            try {
                mac = new JSONArray(mMac);
                tag = new JSONArray(mTag);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            setProgressing(true);
            WyzeEventPlatform.getInstance().getEventMessgeLists(getContext(), mac, tag, new JSONArray(), "1",
                    loadTime, recordList.get(recordList.size() - 1).getEvent_ts(), 20, 2, new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            WpkToastUtil.showText(getString(R.string.failed));
                            setProgressing(false);
                            fragments.get(currentIndex).showBgPic(false);
                            uiForAiHintVisible(true);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            setProgressing(false);
                            fragments.get(currentIndex).showBgPic(false);
                            uiForAiHintVisible(true);
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response);
                                String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                                String data = jsonObject.has("data") ? jsonObject.getString("data") : null;

                                if (code.equals("1")) {

                                    ArrayList<EventItem> eventList = parseJson(new JSONObject(data));
                                    if (eventList.size() < 20) {
                                        ishasMore = false;
                                    }
                                    Log.d(TAG, "eventList.size()   =   " + eventList.size() + "   " + ishasMore);
                                    for (EventItem item : eventList) {
                                        if (!recordList.contains(item)) {
                                            recordList.add(item);
                                        }
                                    }
                                    //添加完毕 刷新ui
                                    fragments.clear();
                                    if (recordList != null && recordList.size() >= 1) {
                                        for (int i = 0; i < recordList.size(); i++) {
                                            FragmentVideoPlayer fragmentVideoPlayer = FragmentVideoPlayer.newInstance(recordList.size(), i);
                                            fragments.add(fragmentVideoPlayer);
                                        }
                                    }
                                    titleAdapter.notifyDataSetChanged();
                                    viewpager.setCurrentItem(currentIndex, true);

                                } else {
                                    WpkToastUtil.showText(getString(R.string.failed));
                                }


                            } catch (JSONException e) {
                                e.printStackTrace();
                                WpkToastUtil.showText(getString(R.string.failed));
                            }

                        }
                    });
        }
    }

    private ArrayList<EventItem> parseJson(JSONObject data) {
        try {
            JSONArray jArray = data.getJSONArray("event_list");
            if (jArray != null) {
                ArrayList<EventItem> infoList = new ArrayList<>();
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject jobj = jArray.getJSONObject(i);
                    EventItem info = new EventItem();
                    info.setEventID(jobj.getString("event_id"));
                    info.setDeviceMac(jobj.getString("device_mac"));
                    info.setEventModel(jobj.getString("device_model"));
                    info.setEvent_category(jobj.getInt("event_category"));
                    info.setEvent_value(jobj.getString("event_value"));
                    info.setEvent_ts(jobj.getLong("event_ts"));
                    info.setRead_state(jobj.getInt("read_state"));
                    JSONArray fileArr;
                    fileArr = jobj.isNull("file_list") ? null : jobj.getJSONArray("file_list");
                    if (fileArr != null && fileArr.length() > 0) {
                        JSONObject jobFile;
                        for (int r = 0; r < fileArr.length(); r++) {
                            jobFile = fileArr.getJSONObject(r);
                            if (jobFile.getInt("type") == 1) {
                                info.setPicUrl(jobFile.getString("url"));
                                info.setAlarm_pic_status(jobFile.getInt("status"));
                                info.setAlarm_pic_encryption_algorithm(jobFile.getInt("en_algorithm"));
                                info.setAlarm_pic_encryption_password(jobFile.getString("en_password"));
                                if (info.getType() == 2) {
                                } else {
                                    info.setFile_id(jobFile.getString("file_id"));
                                }
                            } else if (jobFile.getInt("type") == 2) {
                                info.setFile_id(jobFile.getString("file_id"));
                                info.setVideoUrl(jobFile.getString("url"));
                                info.setAlarm_video_status(jobFile.getInt("status"));
                                info.setAlarm_video_encryption_algorithm(jobFile.getInt("en_algorithm"));
                                info.setAlarm_video_encryption_password(jobFile.getString("en_password"));
                                info.setVideoType(EventItem.RECORD_TYPE_ALARM);
                            }
                        }
                    }
                    JSONObject jobParams;
                    jobParams = jobj.getJSONObject("event_params");
                    JSONArray paramsArr;
                    paramsArr = jobParams.isNull("link_device_mac_list") ? null : jobParams.getJSONArray("link_device_mac_list");
                    if (paramsArr != null && paramsArr.length() > 0) {
                        ArrayList<String> macList = new ArrayList<>();
                        for (int p = 0; p < paramsArr.length(); p++) {
                            macList.add(paramsArr.getString(p));
                        }
                        info.setEventLinkMacList(macList);
                    }

                    if (jobParams.has("beginTime")) {
                        info.setStart_time(jobParams.optLong("beginTime"));
                    } else {
                        info.setStart_time(info.getEvent_ts());
                    }
                    if (jobParams.has("endTime")) {
                        info.setEnd_time(jobParams.optLong("endTime"));
                    }

                    //触发传感器的设备
                    JSONObject triggerDevice = jobParams.isNull("trigger_device") ? null : jobParams.getJSONObject("trigger_device");
                    if (triggerDevice != null) {
                        String device_mac = triggerDevice.isNull("device_mac") ? "" : triggerDevice.getString("device_mac");
                        String device_model = triggerDevice.isNull("device_model") ? "" : triggerDevice.getString("device_model");
                        String nick_name = triggerDevice.isNull("nick_name") ? "" : triggerDevice.getString("nick_name");
                        info.setTriggerDeviceMac(device_mac);
                        info.setTriggerDeviceModel(device_model);
                        info.setTriggerDeviceName(nick_name);
                    }
                    //taglist
                    JSONArray tag_list = jobj.has("tag_list") ? jobj.getJSONArray("tag_list") : null;
                    if (tag_list != null) {
                        for (int n = 0; n < tag_list.length(); n++) {
                            int tag = tag_list.getInt(n);
                            if (tag == WyzeEventSelectModel.PERSON_TYPE) {
                                info.setPerson(true);
                            } else if (tag == WyzeEventSelectModel.VEHICLE_TYPE) {
                                info.setVehicle(true);
                            }
                        }
                    }
                    infoList.add(info);
                }
                Log.d(TAG, "list size=" + infoList.size());
                return infoList;
            } else {
                Log.i(TAG, "data is null");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    private EventItem parseJsonForInfo(JSONObject data) {
        EventItem info = null;
        try {
            info = new EventItem();
            info.setEventID(data.getString("event_id"));
            info.setDeviceMac(data.getString("device_mac"));
            info.setEventModel(data.getString("device_model"));
            info.setEvent_category(data.getInt("event_category"));
            info.setEvent_value(data.getString("event_value"));
            info.setEvent_ts(data.getLong("event_ts"));
            info.setRead_state(data.getInt("read_state"));
            JSONArray fileArr;
            fileArr = data.isNull("file_list") ? null : data.getJSONArray("file_list");
            if (fileArr != null && fileArr.length() > 0) {
                JSONObject jobFile;
                for (int r = 0; r < fileArr.length(); r++) {
                    jobFile = fileArr.getJSONObject(r);
                    if (jobFile.getInt("type") == 1) {
                        info.setPicUrl(jobFile.getString("url"));
                        info.setAlarm_pic_status(jobFile.getInt("status"));
                        info.setAlarm_pic_encryption_algorithm(jobFile.getInt("en_algorithm"));
                        info.setAlarm_pic_encryption_password(jobFile.getString("en_password"));
                        if (info.getType() == 2) {
                        } else {
                            info.setFile_id(jobFile.getString("file_id"));
                        }
                    } else if (jobFile.getInt("type") == 2) {
                        info.setFile_id(jobFile.getString("file_id"));
                        info.setVideoUrl(jobFile.getString("url"));
                        info.setAlarm_video_status(jobFile.getInt("status"));
                        info.setAlarm_video_encryption_algorithm(jobFile.getInt("en_algorithm"));
                        info.setAlarm_video_encryption_password(jobFile.getString("en_password"));
                        info.setVideoType(EventItem.RECORD_TYPE_ALARM);
                    }
                }
            }
            JSONObject jobParams;
            jobParams = data.getJSONObject("event_params");
            JSONArray paramsArr;
            paramsArr = jobParams.isNull("link_device_mac_list") ? null : jobParams.getJSONArray("link_device_mac_list");
            if (paramsArr != null && paramsArr.length() > 0) {
                ArrayList<String> macList = new ArrayList<>();
                for (int p = 0; p < paramsArr.length(); p++) {
                    macList.add(paramsArr.getString(p));
                }
                info.setEventLinkMacList(macList);
            }

            if (jobParams.has("beginTime")) {
                info.setStart_time(jobParams.optLong("beginTime"));
            } else {
                info.setStart_time(info.getEvent_ts());
            }
            if (jobParams.has("endTime")) {
                info.setEnd_time(jobParams.optLong("endTime"));
            }

            //触发传感器的设备
            JSONObject triggerDevice = jobParams.isNull("trigger_device") ? null : jobParams.getJSONObject("trigger_device");
            if (triggerDevice != null) {
                String device_mac = triggerDevice.isNull("device_mac") ? "" : triggerDevice.getString("device_mac");
                String device_model = triggerDevice.isNull("device_model") ? "" : triggerDevice.getString("device_model");
                String nick_name = triggerDevice.isNull("nick_name") ? "" : triggerDevice.getString("nick_name");
                info.setTriggerDeviceMac(device_mac);
                info.setTriggerDeviceModel(device_model);
                info.setTriggerDeviceName(nick_name);
            }
            //taglist
            JSONArray tag_list = data.has("tag_list") ? data.getJSONArray("tag_list") : null;
            if (tag_list != null) {
                for (int n = 0; n < tag_list.length(); n++) {
                    int tag = tag_list.getInt(n);
                    if (tag == 101) {
                        info.setPerson(true);
                    } else if (tag == 102) {
                        info.setVehicle(true);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    //todo 下载模块---------------

    /**
     * 下载模块
     */
    public void getFileURL() {
        Log.i(TAG, "getFileURL --- ");
        if (isNetworkAvailable()) {
            //显示控件
            Log.d(TAG, "网络可用");
            videoFile = null;
            downFileLength = 0;
            olddownFileLength = 0;
            currentmills = 0;
            isDowload = false;
            AnimLoading.show(getActivity(), playerHandler, rl_content, 1000 * 60, "download video");
            hidePlayIcon();
            iv_play_icon.setSelected(false);

            //执行下载

            //wyze 云下载

            //更新下载地址
            WyzeEventPlatform.getInstance().getEventInfo(getContext(), mRecord.getEventID(), mRecord.getDeviceMac(), new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                }

                @Override
                public void onResponse(String response, int id) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response);
                        String code = jsonObject.has("code") ? jsonObject.getString("code") : "-1";
                        String data = jsonObject.has("data") ? jsonObject.getString("data") : null;

                        if (code.equals("1") && data != null) {
                            final EventItem ei = parseJsonForInfo(new JSONObject(data));
                            if (CommonMethod.isStrNotNull(ei.getVideoUrl())) {
                                try {
                                    new Thread() {
                                        @Override
                                        public void run() {
                                            if (AlarmVideoProgress.isDownload) {
                                                AlarmVideoProgress.stopDownloadVideo = true;
                                                while (AlarmVideoProgress.isDownload) {
                                                }
                                            }
                                            down_videoUrl = ei.getVideoUrl();
                                            down_fileName = ei.getVideoFileName();
                                            videoPath = C.newVideoPath;
                                            AlarmVideoProgress.downloadVideo(ei.getVideoUrl(), C.newVideoPath, ei.getVideoFileName(), playerHandler);
                                        }
                                    }.start();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                Log.d(TAG, "get video file : url is null");
                                playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                                return;
                            }
                        } else {
                            playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                    }

                }
            });

        } else {
            Log.d(TAG, "网络不可用");
            AnimLoading.cancel();
            playerHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
        }

    }


    //针对非系统影音资源文件夹
    public static void insertIntoMediaStore(Context context, boolean isVideo, File saveFile, long createTime) {
        ContentResolver mContentResolver = context.getContentResolver();
        if (createTime == 0)
            createTime = System.currentTimeMillis();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.TITLE, saveFile.getName());
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, saveFile.getName());
        //值一样，但是还是用常量区分对待
        values.put(isVideo ? MediaStore.Video.VideoColumns.DATE_TAKEN
                : MediaStore.Images.ImageColumns.DATE_TAKEN, createTime);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, System.currentTimeMillis());
        values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
        if (!isVideo)
            values.put(MediaStore.Images.ImageColumns.ORIENTATION, 0);
        values.put(MediaStore.MediaColumns.DATA, saveFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.SIZE, saveFile.length());
        values.put(MediaStore.MediaColumns.MIME_TYPE, isVideo);
        //插入
        mContentResolver.insert(isVideo
                ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                : MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    public static ContentValues getVideoContentValues(Context paramContext, File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put(MediaStore.Video.Media.TITLE, paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/mp4");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    /**
     * 检查网络是否可用
     *
     * @return 是否
     */
    public boolean isNetworkAvailable() {
        ConnectivityManager manager = null;
        try {
            manager = (ConnectivityManager) getActivity()
                    .getApplicationContext().getSystemService(
                            Context.CONNECTIVITY_SERVICE);
        } catch (Exception e) {
            Log.i(TAG, "isNetworkAvailable  error" + e.getMessage());
        }
        if (manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        return !(networkinfo == null || !networkinfo.isAvailable());
    }

    /**
     * 下载失败刷新UI
     */
    private void UiForDownloadFaill() {
        if (isDowload) {
            Toast.makeText(getContext(), R.string.event_download_failed, Toast.LENGTH_LONG).show();
        } else {
            //回归状态
            try {
                filmLength = 0;
                downFileLength = 0;
                olddownFileLength = 0;
                currentmills = 0;
                uiForPlayStop();
                playerHandler.removeMessages(AlarmVideoProgress.DOWN_FILE_FAILED);
                Log.d(TAG, "download failed");
                Toast.makeText(this, "Download failed", Toast.LENGTH_SHORT).show();
//                    Toast.makeText(context, getString(R.string.wyze_alarm_video_download_fail), Toast.LENGTH_SHORT).show();
//                new OneBtnDialog(getActivity(), getString(R.string.wyze_alarm_video_download_fail), getString(R.string.ok)).show();
                if (new File(mRecord.getVideoFilePath(C.newVideoPath)).exists()) {
                    new File(mRecord.getVideoFilePath(C.newVideoPath)).delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //失败之后再次下载
    private void downFailed() {
        Log.d(TAG, "下载失败。。。downFailed");
        if (new File(mRecord.getVideoFilePath(C.newVideoPath)).exists()) {
            new File(mRecord.getVideoFilePath(C.newVideoPath)).delete();
        }
        if (!new File(mRecord.getVideoFilePath(C.newVideoPath)).exists()) {
            playerHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getFileURL();
                }
            }, 500);
        }
    }

    //中断下载
    private void interruptDownload() {
        Log.d(TAG, "interruptDownload。。。downFailed");
        if (new File(mRecord.getVideoFilePath(C.newVideoPath)).exists()) {
            new File(mRecord.getVideoFilePath(C.newVideoPath)).delete();
        }
        filmLength = 0;
        downFileLength = 0;
        olddownFileLength = 0;
        currentmills = 0;
        uiForPlayStop();
        playerHandler.removeMessages(AlarmVideoProgress.DOWN_FILE_FAILED);
    }


    //todo 初始化播放器-----------

    private void initPlayer() {
        Log.e(TAG, "initPlayer");
        if (surfaceHolder == null || !surfaceHolder.getSurface().isValid()) {
            initSurface();
            return;
        }
        if (mPlayer != null) {
            try {
                mPlayer.prepare();
            } catch (Exception e) {
                e.printStackTrace();
                mPlayer.reset();
                try {
                    mPlayer.setDataSource(videoFile.getPath());
                    mPlayer.prepare();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                return;
            }
            mPlayer.seekTo(seekBar.getProgress());
            mPlayer.start();
            playerHandler.obtainMessage(MSG_HIDE_BG_PIC).sendToTarget();
            return;
        } else {
            Log.d(TAG + "initPlayer", "new mediaplayer");
            mPlayer = new MediaPlayer();
            mPlayer.setDisplay(surfaceHolder);
        }
        try {
            Log.d(TAG, "file path = " + videoFile.getPath());
            mPlayer.setDataSource(videoFile.getPath());
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(final MediaPlayer mp) {
                    Log.e(TAG, "播放完毕！！isOnError=" + isOnError);
                    WyzeCMCPromptManger.getInstance().init(getActivity()).showCmcPromptDialog();//查看是否弹出CMC free trail 弹窗
                    uiForRePlayStop();
                    clearKeepScreenOn();
                    isPause = false;
                    if (isOnError) {
                        mp.reset();
                        try {
                            mp.setDataSource(videoFile.getPath());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        isOnError = false;
                    } else {
                        String seektime = totalDuration + "/" + totalDuration;
                        tv_startTime.setText(seektime);
                        tv_alarm_startTime_land.setText(seektime);
                        playerHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                String seektime = getVideoDurationStr(0) + "/" + totalDuration;
                                tv_startTime.setText(seektime);
                                tv_alarm_startTime_land.setText(seektime);
                                seekBar.setProgress(0);
                                sb_alarm_seekbar_land.setProgress(0);
                            }
                        }, 200);
                        mPlayer.stop();
                        showPopup();
                    }
                }
            });
            mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.e(TAG, "播放出错！！" + what + "   " + extra);
                    isOnError = true;
                    uiForRePlayStop();
                    return false;
                }
            });
            mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.e(TAG, "准备就绪！！ hasAudioTrack=" + hasAudioTrack + "   visible=");
                    playerHandler.sendEmptyMessageDelayed(MSG_HIDE_BG_PIC, 1000);
                    keepScreenOn();
                    initAudioPlayer();
                    isPause = false;
                    isPlayOver = false;
                    mPlayer.seekTo(seekBar.getProgress());
                    hidePlayIcon();
                    iv_play_icon.setImageDrawable(getResources().getDrawable(R.drawable.selector_play_video, null));
                    iv_play_icon.setSelected(false);
                    seekBar.setMax(mPlayer.getDuration());
                    sb_alarm_seekbar_land.setMax(mPlayer.getDuration());
                    mp.start();
                    runProgUpdater("player onPrepared");
                }
            });
            mPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    Log.e(TAG, "进度拖放完毕！！");
                    if (playAudioThread != null) {
                        if (playAudioThread.isRunOver()) {
                            resumeSound();
                        } else {
                            try {
                                playAudioThread.setStartPercentage((float) mp.getCurrentPosition() / (float) mp.getDuration());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        Log.e(TAG, "playAudioThread is null");
                    }
                }
            });
            mPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            Log.e(TAG, "--IllegalArgumentException--");
        } catch (SecurityException e) {
            e.printStackTrace();
            Log.e(TAG, "--SecurityException--");
        } catch (IllegalStateException e) {
            e.printStackTrace();
            Log.e(TAG, "--IllegalStateException--");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "--IOException--e" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "--Exception--e" + e.getMessage());
        }

        mPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    iv_default_bg.setVisibility(View.GONE);
//                    playerHandler.sendEmptyMessageDelayed(DELAY_DISPLAY, 1000);
                }
                return false;
            }
        });
    }

    private boolean isDBModel(){
        return BindableDevice.MODEL_WYZE_DB.equals(deviceModel) || BindableDevice.MODEL_WYZE_DB_S.equals(deviceModel);
    }

    private DBPhotoLiveView dbPhotoLiveView;
    private void initCMCPlayer() {

        setLayoutPosition();

        if(isDBModel()){
           initDBCMCLayout();
        }else{

            if (iv_video_display == null) {
                iv_video_display = new ImageView(DBKvsEventPlayerActivity.this);
                iv_video_display.setBackgroundColor(getResources().getColor(R.color.color_002632));
            }

            frameLayout.removeAllViews();
            initCMCLayout();
            frameLayout.addView(iv_video_display);
            restoreShowArea();
        }

    }

    /**
     * 设置布局位置
     */
    private void setLayoutPosition(){

        if(isDBModel() &&  mVideoMode != VIDEO_COMMON){
            Log.i(TAG, "setLayoutPosition: 显示门铃播放");

            dbPhotoLiveView.setVisibility(View.VISIBLE);
            frameLayout.setVisibility(View.GONE);
            ((RelativeLayout.LayoutParams)rl_control_bar.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.live_view);

            RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) viewpager.getLayoutParams();
            param.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.live_view);
            viewpager.setLayoutParams(param);

        }else{

            Log.i(TAG, "setLayoutPosition: 隐藏门铃播放");

            dbPhotoLiveView.setVisibility(View.GONE);
            frameLayout.setVisibility(View.VISIBLE);
            ((RelativeLayout.LayoutParams)rl_control_bar.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.fl_video);

            RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) viewpager.getLayoutParams();
            param.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.fl_video);
            viewpager.setLayoutParams(param);

        }

    }


    private void initSurface() {
        Log.d(TAG, "initSurface: "+dbPhotoLiveView.getVisibility());

        if(dbPhotoLiveView != null && dbPhotoLiveView.getVisibility() == View.VISIBLE){
            dbPhotoLiveView.setVisibility(View.GONE);

        }

        setLayoutPosition();

        sfv_videoplay = new SurfaceView(this);
        frameLayout.removeAllViews();
        initSurfaceLayout();
        frameLayout.addView(sfv_videoplay);
        surfaceHolder = sfv_videoplay.getHolder();
        sfv_videoplay.setZOrderOnTop(false);
        sfv_videoplay.setZOrderMediaOverlay(false);
        surfaceHolder.setFormat(PixelFormat.RGB_565);
        surfaceHolder.addCallback(this);
        restoreShowArea();
    }


    private void initDBCMCLayout(){
        RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) dbPhotoLiveView.getLayoutParams();
        if(isFullScreen){
            int mWidthPixels = CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this));
            p.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            p.height = (int) RelativeLayout.LayoutParams.MATCH_PARENT;
        }else{
            int mWidthPixels = CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this));
            p.width = mWidthPixels;
            p.height = (int) (4 * mWidthPixels / 3.0f);
        }
        dbPhotoLiveView.setLayoutParams(p);
    }


    private void initSurfaceLayout() {
        Log.d(TAG, "initSurfaceLayout isFullScreen=" + isFullScreen+"..."+isDBModel());
        if(isDBModel()){
            if (isFullScreen) {
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                        CommonMethod.getHasVirtualKeyHeight(getActivity()),
                        CommonMethod.getHasVirtualKeyWidth(getActivity()));
                params.gravity = Gravity.CENTER;
                sfv_videoplay.setLayoutParams(params);
            } else {
                int mWidthPixels = CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this));
                int height = (int) (4 * mWidthPixels / 3.0f);
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(mWidthPixels, height);
                sfv_videoplay.setLayoutParams(params);
            }
        }else{
            screenWidth = CommonMethod.getHasVirtualKeyWidth(getActivity());
            screenHeight = isFullScreen ? CommonMethod.getHasVirtualKeyHeight(getActivity()) : screenWidth * 9 / 16;
            if (isFullScreen) {
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(screenHeight, screenWidth);
                params.gravity = Gravity.CENTER;
                sfv_videoplay.setLayoutParams(params);
            } else {
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(screenWidth, screenHeight);
//            params.gravity = Gravity.CENTER;
                sfv_videoplay.setLayoutParams(params);
            }
        }

    }

    private void initCMCLayout() {
        Log.d(TAG, "initCMCLayout isFullScreen=" + isFullScreen);
        FrameLayout.LayoutParams params = null;
        if (isFullScreen) {
            params = new FrameLayout.LayoutParams(CommonMethod.getWindowVerticalHeight(new WeakReference<Activity>(this)), CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this)));
            params.gravity = Gravity.CENTER;
        } else {
            params = new FrameLayout.LayoutParams(CommonMethod.getWindowVerticalWidth(new WeakReference<Activity>(this)), CommonMethod.getVideoViewVerticalHeight(new WeakReference<Activity>(this)));
            params.gravity = Gravity.CENTER;
        }

        if(iv_video_display != null){
            iv_video_display.setLayoutParams(params);
        }

    }


    private void resumeSound() {
        Log.i(TAG, "resumeSound");
        Log.i(TAG, "Play Thread:" + playAudioThread.getState());
        Log.i(TAG, "seekBar.getProgress()=" + seekBar.getProgress() + "    seekBar.getMax()=" + seekBar.getMax());
        if (playAudioThread == null || playAudioThread.getState() == Thread.State.TERMINATED) {
            playAudioThread = new PlayAudioThread((float) seekBar.getProgress() / (float) seekBar.getMax());
            playAudioThread.start();
        }
        mPCMAudioTrack.play();
        playAudioThread.setPause(false);
    }

    private void pauseSound() {
        Log.i(TAG, "pauseSound");
        if (playAudioThread != null)
            playAudioThread.setPause(true);
        if (mPCMAudioTrack != null) {
            mPCMAudioTrack.flush();
            mPCMAudioTrack.pause();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        Log.i(TAG, "surfaceCreated:"+videoFile);
        if (videoFile != null) {
            playerHandler.sendEmptyMessage(MSG_START_PLAY);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        Log.d(TAG, "surfaceDestroyed");
    }

    /**
     * @param fromFile 被复制的文件
     * @param toFile   复制的目录文件
     * @param rewrite  是否重新创建文件
     *                 <p>
     *                 <p>文件的复制操作方法
     */
    public void copyfile(File fromFile, File toFile, Boolean rewrite) {

        if (!fromFile.exists()) {
            return;
        }

        if (!fromFile.isFile()) {
            return;
        }
        if (!fromFile.canRead()) {
            return;
        }
        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }
        if (toFile.exists() && rewrite) {
            toFile.delete();
        }


        try {
            FileInputStream fosfrom = new FileInputStream(fromFile);
            FileOutputStream fosto = new FileOutputStream(toFile);

            byte[] bt = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            String s = System.currentTimeMillis() + "";
            byte[] sb = s.getBytes();


            fosto.write(sb, 0, sb.length);
            //关闭输入、输出流
            fosfrom.close();
            fosto.close();


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取ContentResolve对象，来操作插入视频
        ContentResolver localContentResolver = getContext().getContentResolver();
        ContentValues localContentValues = getVideoContentValues(getContext(), toFile, System.currentTimeMillis());
        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
        Toast toast = Toast.makeText(getContext(), R.string.save_to_album, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM, Gravity.CENTER, WyzeEventDisplayUtils.dip2px(120));
        toast.show();
        setViewClickable(true);
    }

    public void getDownloadFileURL(String URL, String title) {
        shareUrl = URL;
        shareTitle = System.currentTimeMillis() + ".mp4";
        title = shareTitle;
        Log.i(TAG, "galleryPath:" + galleryPath);
        String s = galleryPath + title;
//        File tempFile = new File(s);
//        Log.i(TAG, "jumpDownload url=" + s);
//        if (!tempFile.exists()) {

//        } else {
//            Toast.makeText(getContext(), "This video has been downloaded", Toast.LENGTH_SHORT).show();
//        }

        File videofile = new File(mRecord.getVideoFilePath(C.newVideoPath));
        String videoFilePath = mRecord.getVideoFilePath(C.newVideoPath);
        if (videofile.exists()) {
            copyfile(videofile, new File(s), false);
            Log.i(TAG, "文件拷贝成功！！");
        } else {
            if (!isNetworkAvailable()) {
                Toast toast = Toast.makeText(this, R.string.event_download_failed, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.BOTTOM, Gravity.CENTER, WyzeEventDisplayUtils.dip2px(120));
                toast.show();
                setViewClickable(true);
            } else {
                getDownloadFile(URL, title);
            }
        }


    }

    private void setViewClickable(boolean isCanClick) {
        if (isCanClick) {
            iv_alarm_download.setEnabled(true);
        } else {
            iv_alarm_download.setEnabled(false);
        }
    }

    private void getDownloadFile(final String URL, final String title) {
        if (isNetworkAvailable()) {
            //显示控件
            Log.d(TAG, "网络可用");
//            downLoadUI();
            isDownloadFileFinsh = false;
            Log.d(TAG, "网络可用isDownloadFileFinsh=" + isDownloadFileFinsh);
            if (!isDownloadFileFailed) {
                downloadProgress();
            }
            //执行下载
            //wyze 云下载
            if (CommonMethod.isStrNotNull(URL)) {
                try {
                    new Thread() {
                        @Override
                        public void run() {
                            AlarmVideoProgress.downloadVideo(URL, galleryPath, title, downloadHandler);
                        }
                    }.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.d(TAG, "get video file : url is null");
                downloadHandler.sendEmptyMessage(AlarmVideoProgress.DOWN_FILE_FAILED);
                return;
            }
        } else {
            Log.d(TAG, "网络不可用");
            isDownloadFileFinsh = false;

        }
    }

    /**
     * 下载进度改为1分钟倒计时
     */
    CountDownTimer timer;

    private void downloadProgress() {
        Log.d(TAG, "开始倒计时.....");
        mShareDownloadRpb.setProgress(0);
        timer = new CountDownTimer(1000 * 60, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.d(TAG, "还剩" + millisUntilFinished / 1000 + "秒");
                double rate = ((60000 - millisUntilFinished) / 1000) * (100.0 / 60);
                Log.d(TAG, "rate=" + (int) rate);
            }

            @Override
            public void onFinish() {
                Log.d(TAG, "onFinish ......isDownloadFileFinsh" + isDownloadFileFinsh);
                mShareDownloadRpb.setProgress(100);
                if (!isDownloadFileFinsh || isDownloadFileFailed) {
                    mShareDownloadRpb.setVisibility(View.GONE);
                }
            }
        }.start();

    }

    /**
     * 下载模块。图片更新
     */
    @SuppressLint("HandlerLeak")
    private Handler downloadHandler = new ControlHandler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SETDEFAULTIMAGE:
                    //快速滑动易呗回收
//                    if (iv_replay_recover != null) {
//                        iv_replay_recover.setImageBitmap((Bitmap) msg.obj);
//                    }
//                    if (mSurfaceView != null) {
////                        mSurfaceView.setBackgroundDrawable(new BitmapDrawable((Bitmap) msg.obj));
//                    }
                    break;
                //隐藏进度条
                case HIDEBAR:
                    break;
                //点击全屏画面
                case CLICK_SINGLE_VIDEO: {
//                    clickSingleVideo();
                }
                break;
                case AlarmVideoProgress.DOWN_VIDEO_RATE:
                    final int downloadLength = msg.arg1;
                    downFileLength += downloadLength;
                    int rate = (downFileLength * 100) / filmLength;
                    Log.d(TAG, "downFileLength==" + downFileLength + ",filmLength=" + filmLength + "下载进度：" + rate + "%");
                    try {
                        mShareDownloadRpb.setProgress(rate);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //计算一秒的下载速度
                    if (System.currentTimeMillis() - currentmills >= 100) {
                        currentmills = System.currentTimeMillis();
                        int speed = (downFileLength - olddownFileLength) / 1024 * 10;//当前的下载量减去上一秒的总下载量/1024 ：一秒的下载量
//                        Log.i(TAG, "1秒的下载速度为" + speed + "     downFileLength = " + downFileLength + "       olddownFileLength=  " + olddownFileLength);
                        olddownFileLength = downFileLength;
                    }

                    break;
                case AlarmVideoProgress.DOWN_VIDEO_LENGTH:
                    filmLength = msg.arg1;
                    break;
                case AlarmVideoProgress.DOWN_FILE_FINISHED:
                    mShareDownloadRpb.setProgress(100);
                    if (timer != null) {
                        timer.cancel();
                    }
                    this.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isDownloadFileFinsh = true;
                            isDownloadFileFailed = false;
                            galleryPath = galleryPath + shareTitle;
                            Log.i(TAG, "没有加密视频 =" + galleryPath);

                            picThread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!isValid()) {
                                        return;
                                    }
                                    bitmapsFromVideo = CommonMethod.getVideoFirstFrameBitmap(galleryPath, BitmapFactory.decodeResource(getResources(), R.drawable.alarmvideo_bg));
                                    Message message = new Message();
                                    message.what = SETDEFAULTIMAGE;
                                    message.obj = bitmapsFromVideo;
                                    downloadHandler.sendMessage(message);
                                }
                            });
                            picThread.start();

                            File file = new File(galleryPath);
                            //获取ContentResolve对象，来操作插入视频
                            ContentResolver localContentResolver = getContext().getContentResolver();
                            ContentValues localContentValues = getVideoContentValues(getContext(), file, System.currentTimeMillis());
                            Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
                            Toast toast = Toast.makeText(getContext(), R.string.save_to_album, Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.BOTTOM, Gravity.CENTER, WyzeEventDisplayUtils.dip2px(120));
                            toast.show();
                            setViewClickable(true);
                        }
                    }, 100);
                    break;
                case AlarmVideoProgress.DOWN_FILE_FAILED:
                    isDownloadFileFailed = true;
                    downloadFaileCounts++;
                    if (downloadFaileCounts > 10) {
                        downloadFaileCounts = 0;
                        if (timer != null) {
                            timer.cancel();
                        }
                        //回归状态
                        UiForDownloadFaill();
                    } else {
                        downFailed();
                    }
                    break;
                case AlarmVideoProgress.DOWN_FILE_INTERRUPT:
                    isDownloadFileFailed = true;
//                    if (mRecord.isPushAlarm) {
//                        //是推送过来的报警视屏
//                        alarmPushUiForDownloadFaill();
//                    } else {
//                        UiForDownloadFaill();
//                    }
                    downFailed();
                    break;
            }
        }

        /**
         * 下载失败刷新UI
         */
        private void UiForDownloadFaill() {
            //回归状态
            try {
                isDownloadFileFinsh = false;
                downFileLength = 0;
                olddownFileLength = 0;
                currentmills = 0;
                mShareDownloadRpb.setProgress(0);
//                iv_replay_recover.setVisibility(View.VISIBLE);
//                iv_restart.setVisibility(View.VISIBLE);
                this.removeMessages(AlarmVideoProgress.DOWN_FILE_FAILED);
                Log.d(TAG, "download failed");
                if (getContext() != null) {
                    new OneBtnDialog(getActivity(), getString(R.string.wyze_alarm_video_download_fail), getString(R.string.ok)).show();
                }
                if (new File(galleryPath).exists()) {
                    new File(galleryPath).delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 推送报警视屏跳转播放页是下载失败
         */
        private void alarmPushUiForDownloadFaill() {
            //回归状态
            try {
                isDownloadFileFinsh = false;
                downFileLength = 0;
                olddownFileLength = 0;
                currentmills = 0;
                mShareDownloadRpb.setProgress(0);
                if (isFristIn) {
                    isFristIn = false;
                }
                this.removeMessages(AlarmVideoProgress.DOWN_FILE_FAILED);
                //下载
                if (!new File(galleryPath).exists()) {
                    getDownloadFile(shareUrl, shareTitle);
                    return;
                }
                Log.d(TAG, "download failed");
                if (new File(galleryPath).exists()) {
                    new File(galleryPath).delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 请求设备是否绑定person
     */
    public void getCheckAiFeedback() {

        if (mRecord != null) {
//            Device device = WyzeDeviceManager.getInstance().getDeviceFromMac(mRecord.getDeviceMac());
            DeviceModel.Data.DeviceData device = WpkDeviceManager.getInstance().getDeviceModelById(mRecord.getDeviceMac());

            if (device != null) {
                final JSONArray jsonArray = new JSONArray();
                if (device.getUser_role() == 1 && EventModel.isAiCamera(device.getProduct_model())) {
                    jsonArray.put(new AiSelectDevice(device).toJson());
                    OkHttpUtils.getInstance().cancelTag(jsonArray);
                    WyzeEventPlatform.getInstance().getMemberCheckAvailbleDevice(jsonArray, new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.i(TAG, "getCheckAiFeedback onError e = " + e);
                            tv_improve_layout.setVisibility(View.GONE);
                            tv_improve_thanks.setVisibility(View.GONE);

                            try {
                                HashMap<String, Object> serviceMap = new HashMap<>();
                                serviceMap.put("body", jsonArray.toString());
                                Log.i(TAG, "getMemberCheckAvailbleDevice  e serviceMap = " + serviceMap.toString());
                                WyzeStatisticsUtils.logEvent(StatIndex.PID_APP, WpkStatisticsAgent.STATISTICS_WYZE,
                                        4, StatIndex.EV_FULLMOTION_CHECK_SERVICE_AVAILABLE_ERROR,
                                        "errorMsg", e.getMessage(), serviceMap);
                            } catch (Exception ex) {
                                Log.i(TAG, "getMemberCheckAvailbleDevice e = " + ex.getMessage());
                            }
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.i(TAG, "getCheckAiFeedback response = " + response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                int code = jsonObject.getInt("code");
                                if (code == 1) {
                                    if (jsonObject.has("data")) {
                                        JSONArray data = jsonObject.getJSONArray("data");
                                        for (int i = 0; i < data.length(); i++) {
                                            JSONObject jsondevice = data.getJSONObject(i);
                                            String device_id = "";
                                            if (jsondevice.has("device_id")) {
                                                device_id = jsondevice.getString("device_id");
                                            }
                                            if (mRecord != null && TextUtils.equals(mRecord.getDeviceMac(), device_id)) {
                                                if (jsondevice.has("result")) {
                                                    boolean result = jsondevice.getBoolean("result");
                                                    bindlists.put(device_id, result);
                                                    if (result && (mRecord.getEvent_value().equals("1") || mRecord.getEvent_value().equals("13"))) {
                                                        if (isFullScreen) {
                                                            tv_improve_layout.setVisibility(View.GONE);
                                                            tv_improve_thanks.setVisibility(View.GONE);
                                                        } else {
                                                            String sp_report = sharedPreferences.getString(mRecord.getEventID(), "");
                                                            if (!TextUtils.isEmpty(sp_report) && sp_report.equals(is_share)) {
                                                                tv_improve_thanks.setVisibility(View.VISIBLE);
                                                                tv_improve_layout.setVisibility(View.GONE);
                                                            } else {
                                                                tv_improve_layout.setVisibility(View.VISIBLE);
                                                                tv_improve_thanks.setVisibility(View.GONE);
                                                            }
                                                        }
                                                    }
                                                } else {
                                                    tv_improve_layout.setVisibility(View.GONE);
                                                    tv_improve_thanks.setVisibility(View.GONE);
                                                }
                                            } else {
                                                tv_improve_layout.setVisibility(View.GONE);
                                                tv_improve_thanks.setVisibility(View.GONE);
                                            }
                                        }

                                    }
                                } else {
//                                    WpkToastUtil.showText(getString(R.string.failed));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });

                    return;
                }
            } else {
                Log.i(TAG, "getCheckAiFeedback,device is null,mac is " + mRecord.getDeviceMac());
            }
        }
    }

    private void checkPersonFeedback() {

        if (bindlists == null) {
            bindlists = new ArrayMap<>();
        }
        Boolean isperson = bindlists.get(mRecord.getDeviceMac());
        if (isperson != null) {
            if (isperson && (Integer.valueOf(mRecord.getEvent_value()) == 1 || Integer.valueOf(mRecord.getEvent_value()) == 13)) {
                String sp_report = sharedPreferences.getString(mRecord.getEventID(), "");
                if (!TextUtils.isEmpty(sp_report) && sp_report.equals(is_share)) {
                    tv_improve_thanks.setVisibility(View.VISIBLE);
                    tv_improve_layout.setVisibility(View.GONE);
                } else {
                    tv_improve_layout.setVisibility(View.VISIBLE);
                    tv_improve_thanks.setVisibility(View.GONE);

                }
            } else {
                tv_improve_layout.setVisibility(View.GONE);
                tv_improve_thanks.setVisibility(View.GONE);
            }
        } else {
            getCheckAiFeedback();
        }
    }

    private void showPopup() {
        try {
            if (bindlists == null) {
                bindlists = new ArrayMap<>();
            }
            Boolean isperson = bindlists.get(mRecord.getDeviceMac());

            boolean ismotion = Integer.valueOf(mRecord.getEvent_value()) == 1;
            if (isperson == null || !isperson || !ismotion) {
                return;
            }

            //弹窗
            Long popupTime = SPTools.getLongValue(getContext(), SPTools.KEY_ALARM_FEEDBACK_POPUP_TIME);
            Log.i(TAG, "上次时间为  popupTime = " + popupTime + " 当前时间 是否与上次间隔 = " + (System.currentTimeMillis() / 1000 - popupTime) / 60 / 60 / 24);
            if (getRom() && (System.currentTimeMillis() / 1000 - popupTime) / 60 / 60 / 24 > FEEDBACK_TIME) {
//            if (getRom() && (System.currentTimeMillis() / 1000 - popupTime) / 60 > FEEDBACK_TIME) {
//            if (true) {
                SPTools.setLongValue(getContext(), SPTools.KEY_ALARM_FEEDBACK_POPUP_TIME, System.currentTimeMillis() / 1000);
                if (dialog == null || !dialog.isShowing()) {
                    dialog = EventBottomFeedbackDialog.createSure(getActivity());
                    dialog.setOnListener(new EventBottomFeedbackDialog.OnHintDialogListener() {

                        @Override
                        public void onClickDone(boolean isSee, boolean isShare) {
                            sendRequest(isSee, isShare);
                            popupSuccess();
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
                    Log.i(TAG, "showPopup   show");
                    dialog.show();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void popupSuccess() {
        EventBottomSuccessDialog dialog = EventBottomSuccessDialog.createSure(getActivity());
        dialog.show();
    }

    private class PlayerHandler extends ControlHandler {
        private String playUrl = "";
        private int nCount = 0;

        @Override
        public void handleMessage(Message msg) {
            /*if (msg.what != CHANGE_START_TIME && msg.what != com.HLApi.utils.MessageIndex.DISPLAY_VIDEO_FRAME
                    && msg.what != com.HLApi.utils.MessageIndex.REFRESH_VIDEO_INFO) {
                Log.i(TAG, "PlayerHandler " + msg.what);
            }*/
            switch (msg.what) {
                case MSG_HIDE_BG_PIC: {
                    fragments.get(currentIndex).showBgPic(false);
                    uiForAiHintVisible(true);
                }
                break;
                case MSG_HIDE_LAND_BAR: {
                    if (mLandTitleBar.getVisibility() == View.VISIBLE) {
                        mLandTitleBar.setVisibility(View.GONE);
                    }
                    if (mLandSeekRl.getVisibility() == View.VISIBLE) {
                        mLandSeekRl.setVisibility(View.GONE);
                    }
                    if (ll_right_land.getVisibility() == View.VISIBLE) {
                        ll_right_land.setVisibility(View.GONE);
                    }
                    iv_play_icon.setVisibility(View.GONE);

                }
                break;
                case CHANGE_START_TIME: {
                    if (isDowload) {
                    } else {
                        String seektime = getVideoDurationStr(msg.arg1) + "/" + totalDuration;
                        tv_startTime.setText(seektime);
                        tv_alarm_startTime_land.setText(seektime);
                    }
                }
                break;
                case MessageIndex.DOWNLOAD_VIDEO: {
                    Log.e(TAG, "handleMessage DOWNLOAD_VIDEO arg1=" + msg.arg1 + "   arg2=" + msg.arg2);
                    if (msg.arg1 == MessageIndex.SUCCESS) {
                        videoFile = mRecord.getVideoFile(playerHandler, C.newVideoPath);
                        if (!mRecord.isEncode()) {
                            //未加密视频，直接去播放
                            playerHandler.sendEmptyMessage(MSG_PREPARE_PLAY);
                            Log.i(TAG, "未加密视频，直接去播放");
                        } else {
                            //去解密
                            Log.i(TAG, "去解密");
                            DecryptionVideo(videoFile, mRecord.getAlarm_video_encryption_password());
                        }
                    } else {
                        if (System.currentTimeMillis() - mRecord.getEvent_ts() < 300000) {
                            Toast.makeText(DBKvsEventPlayerActivity.this, R.string.video_uploading, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(DBKvsEventPlayerActivity.this, R.string.timeout_download_video, Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                break;
                case MSG_PREPARE_PLAY: {
                    if (videoFile == null) {
                        Log.d(TAG, "videoFile is null");
                        setVideoData("MSG_PREPARE_PLAY file null");
                    } else {
                        WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_WYZE, 1, StatIndex.WYZE_ALARM_CHECK);
                        fragments.get(viewpager.getCurrentItem()).showBgPic(false);
                        uiForAiHintVisible(true);
                        totalDuration = CommonMethod.getLocalVideoDurationInStr(videoFile.getPath(), "00:00");
                        Log.i(TAG, "mPlayer = " + mPlayer);

                        if (mPlayer == null) {
                            initSurface();
                            audioDataList.clear();
                            hasAudioTrack = getAudioTrack();
                        }



                    }
                }
                break;
                case MSG_START_PLAY: {
                    fragments.get(viewpager.getCurrentItem()).showBgPic(false);
                    uiForAiHintVisible(true);
                    initPlayer();
                }
                break;
                case MSG_SET_VIDEO: {
                    setVideoData(hasSwipedViewPager);
                }
                break;
                case MessageIndex.LOADING_TIME_OUT: {
                    Log.i(TAG, "LOADING_TIME_OUT ");
                    AnimLoading.cancel();
                    Toast.makeText(DBKvsEventPlayerActivity.this, R.string.network_time_out, Toast.LENGTH_SHORT).show();
                }
                break;
                case AlarmVideoProgress.DOWN_VIDEO_CONNECTING: {
                    Log.i(TAG, "DOWN_VIDEO_CONNECTING -- ");
                    AnimLoading.cancel();
                    AnimLoading.show(getActivity(), playerHandler, rl_content, 1000 * 60, "download video");
                    hidePlayIcon();
                    iv_play_icon.setSelected(true);
                }
                break;
                case AlarmVideoProgress.DOWN_VIDEO_RATE: {
                    int downloadLength = msg.arg1;
                    downFileLength += downloadLength;
                    int rate = (downFileLength * 100) / filmLength;
                    Log.d(TAG, "DOWN_VIDEO_RATE   downFileLength==" + downFileLength + ",filmLength=" + filmLength + "下载进度：" + rate + "%");

                    //计算一秒的下载速度
                    if (System.currentTimeMillis() - currentmills >= 100) {
                        currentmills = System.currentTimeMillis();
                        int speed = (downFileLength - olddownFileLength) / 1024 * 10;//当前的下载量减去上一秒的总下载量/1024 ：一秒的下载量
//                        Log.i(TAG, "1秒的下载速度为" + speed + "     downFileLength = " + downFileLength + "       olddownFileLength=  " + olddownFileLength);
                        olddownFileLength = downFileLength;
                    }

                    if (iv_play_icon.getVisibility() == View.VISIBLE) {
                        hidePlayIcon();
                        iv_play_icon.setSelected(true);
                    }
                }
                break;
                case AlarmVideoProgress.DOWN_VIDEO_LENGTH: {
                    Log.i(TAG, "DOWN_VIDEO_LENGTH --  ");
                    filmLength = msg.arg1;
                }
                break;
                case AlarmVideoProgress.DOWN_FILE_FINISHED: {
                    Log.i(TAG, "DOWN_FILE_FINISHED --  ");
                    filmLength = 0;
                    downFileLength = 0;

                    //结束加载动画
                    AnimLoading.cancel();
                    this.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            videoFile = mRecord.getVideoFile(playerHandler, C.newVideoPath);
                            Log.i(TAG, "videoFile:"+videoFile.getAbsolutePath());

                            if (isDBModel()){
                                //保留三个视频
                                keepThreeVideo();
                                rotateDBFile();

                            }else{
                                if (!mRecord.isEncode()) {
                                    if (isDowload) {
                                        File file = new File(galleryPath);
                                        //获取ContentResolve对象，来操作插入视频
                                        ContentResolver localContentResolver = getContext().getContentResolver();
                                        ContentValues localContentValues = getVideoContentValues(getContext(), file, System.currentTimeMillis());
                                        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
                                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
                                    } else {
                                        //保留三个视频
                                        keepThreeVideo();
                                        //未加密视频，直接去播放
                                        playerHandler.sendEmptyMessage(MSG_PREPARE_PLAY);
                                        Log.i(TAG, "未加密视频，直接去播放");
                                    }
                                } else {
                                    //去解密
                                    Log.i(TAG, "去解密");
                                    DecryptionVideo(videoFile, mRecord.getAlarm_video_encryption_password());
                                }
                            }
                        }
                    }, 100);
                }
                break;
                case AlarmVideoProgress.DOWN_FILE_FAILED: {
                    Log.i(TAG, "DOWN_FILE_FAILED --  ");
                    downloadFaileCount++;
                    if (downloadFaileCount > 10) {
                        downloadFaileCount = 0;
                        //回归状态
                        UiForDownloadFaill();
                    } else {
                        downFailed();
                    }
                }
                break;
                case AlarmVideoProgress.DOWN_FILE_INTERRUPT: {
                    Log.i(TAG, "DOWN_FILE_INTERRUPT --  ");
                    interruptDownload();
                }
                break;
                case MessageIndex.CLOUD_EVENT_FEED_BACK: {
                    rl_loading.setVisibility(View.GONE);
                    wyzeEventShareDialog.dismiss();
                    if (msg.arg1 == MessageIndex.SUCCESS) {
                        uiWriteCopywriter();
                    }
                }
                break;
                case MessageIndex.ROTARY: {
                    Log.i(TAG + " cameraRotaryByStep", "horSteps=" + msg.arg1 + "  verSteps=" + msg.arg2);
                    if (com.HLApi.utils.C.isInReplayMode || !ConnectControl.instance(mMac).getProductModel().equals(EventModel.MODEL_WYZECPAN)) {
                        return;
                    } else {
                        ConnectControl.instance(mMac).func_setRotaryByDegree(msg.arg1, msg.arg2, ConnectControl.instance(mMac).getRotateSpeed(DBKvsEventPlayerActivity.this, 5));
                    }
                }
                break;
                case SET_PLAYBACK_SCREEN: { //回放走onStart之后的界面竖屏显示
                    setScreen(false);
                }
                break;
                case com.HLApi.utils.MessageIndex.REFRESH_VIDEO_INFO: {
                    if (msg.getData().getBoolean("isDashFrame")) {
                        if (!hasReceiveIFrame) {
                            receiveFirstIFrame(true);
                        }
                        if (mVideoMode != VIDEO_COMMON) {
                            long fus = msg.getData().getLong("tsUs");
                            if (fus < lastFrameUs) {
                                Log.e(TAG, "REFRESH_VIDEO_INFO: 乱序不播, fus=" + fus + "   lastFrameUs=" + lastFrameUs);
                                return;
                            } else {
                                lastFrameUs = fus;
                            }
                        }

                        // FIXME: 2019/7/25 需要修改丢包进度问题REFR
                        if (mVideoMode == VIDEO_DASH_PLAYBACK) {
                            int progress = DashManager.instance().tsInMs2Prog(msg.getData().getLong("tsUs") / 1000L, isFullScreen ? sb_alarm_seekbar_land.getMax() : seekBar.getMax());
                            if (progress != seekBar.getMax()) {
                                seekBar.setProgress(progress);
                                sb_alarm_seekbar_land.setProgress(progress);
                            }
                        } else {
                            if (dashPlaybackEndTsInSec == 0L) {
                                dashPlaybackEndTsInSec = msg.arg2;
                            }
                            if (seekBar.getProgress() != seekBar.getMax()) {
                                int progress = DashManager.instance().tsInMs2Prog(msg.getData().getLong("tsUs") / 1000L, isFullScreen ? sb_alarm_seekbar_land.getMax() : seekBar.getMax());
                                seekBar.setProgress(progress);
                                sb_alarm_seekbar_land.setProgress(progress);
                            }
                        }

                        if(isDBModel()){
                            if(msg.obj != null){
                                this.obtainMessage(com.HLApi.utils.MessageIndex.DB_DISPLAY_DASH, msg.getData().getInt("resolution"), -1, msg.obj).sendToTarget();
                            }
                        }else{
                            if (!DashDecodeController.useMediaCodec && msg.obj != null) {
                                this.obtainMessage(com.HLApi.utils.MessageIndex.DISPLAY_VIDEO_FRAME, msg.getData().getInt("resolution"), -1, msg.obj).sendToTarget();
                            }
                        }


                    }
                }
                break;
                case com.HLApi.utils.MessageIndex.DB_DISPLAY_DASH:// 门铃显示


                    if (msg.obj != null) {

                        if (DashManager.instance().getDmStartTsInMs() != 0) {
                            if (iv_default_bg.isShown()) {
                                iv_default_bg.setVisibility(View.GONE);
                            }
                            try{
                                byte[] data = (byte[]) msg.obj;
                                if(dbPhotoLiveView != null){
                                    dbPhotoLiveView.decodeAndDrawing(data, data.length);
                                }
                            }catch (Exception e){

                            }
                        }

                    }
                    AnimLoading.cancel();
                    break;
                case com.HLApi.utils.MessageIndex.DISPLAY_VIDEO_FRAME: {
                    if (iv_video_display != null && msg.obj != null && msg.obj instanceof Bitmap) {
                        iv_video_display.setImageBitmap((Bitmap) msg.obj);
                        if (DashManager.instance().getDmStartTsInMs() != 0) {
                            if (iv_default_bg.isShown()) {
                                iv_default_bg.setVisibility(View.GONE);
                            }
                        }
                        AnimLoading.cancel();
                    }
                }
                break;
                case MessageIndex.CLOUD_GET_KVS_URL_LIVE_AND_PLAYBACK: {
                    if (msg.arg1 == MessageIndex.SUCCESS) {
                        if (mVideoMode == VIDEO_DASH_LIVING && msg.obj instanceof String) {
                            try {
                                playUrl = (String) msg.obj;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            playUrl = "";
                        }
                        isDashPlayError = TextUtils.isEmpty(playUrl);
                        Log.d(TAG, "CLOUD_GET_KVS_URL_LIVE_AND_PLAYBACK playUrl=" + playUrl);
                        if (!TextUtils.isEmpty(playUrl)) {
                            DashManager.instance().setStartTime(mRecord.getStart_time());
                            DashManager.instance().setEndTime(mRecord.getStart_time() + (5 * 60 * 1000));
                            DashManager.instance().initDash(playUrl, DashDecodeController.instance(mMac).getDashCallback(), mVideoMode, playerHandler, true);
                            nCount = 0;
                        } else {
                            nCount++;
                            Log.d(TAG, "CLOUD_GET_KVS_URL_LIVE_AND_PLAYBACK playUrl is null------count=" + nCount);
                            if (dashPlaybackEndTsInSec == 0 && nCount > 3) {
                                Toast.makeText(DBKvsEventPlayerActivity.this, getString(R.string.wyze_event_kvs_playback_url_is_null), Toast.LENGTH_SHORT).show();
                                clear();
                                isPlayOver = true;
                                iv_play_icon.setVisibility(View.VISIBLE);
                                AnimLoading.cancel();
                            } else {
                                playerHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        setDashMode(VIDEO_DASH_LIVING, false);
                                    }
                                }, 1000);
                            }
                        }
                    } else {
                        Toast.makeText(DBKvsEventPlayerActivity.this, getString(R.string.wyze_kvs_get_url_failed), Toast.LENGTH_SHORT).show();
//                        Toast.makeText(DBKvsEventPlayerActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        AnimLoading.cancel();
                    }
                }
                break;
                case MessageIndex.CLOUD_GET_KVS_URL_PLAYBACK: {
                    if (msg.arg1 == MessageIndex.SUCCESS) {
                        if (mVideoMode == VIDEO_DASH_PLAYBACK && msg.arg1 == MessageIndex.SUCCESS && msg.obj instanceof String) {
                            try {
                                playUrl = (String) msg.obj;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            playUrl = "";
                        }
                        isDashPlayError = TextUtils.isEmpty(playUrl);
//                    playUrl = "https://b-647daf39.kinesisvideo.us-west-2.amazonaws.com/dash/v1/getDASHManifest.mpd?SessionToken=CiD7j7Wxp36IBrJP1hghx2F80XTw0dzGtL39br8ZkBo3ZBIQ0V-7MQN4aYvOek5onh9hQBoZ30hFCEiYgaNja6l-kerhqA_ClNrJ6JXl2SIg8gHQDSLu8R55o8foCWYsE0knzdeExAULU0DalmFtUdQ~";
                        Log.d(TAG, "CLOUD_GET_KVS_URL_PLAYBACK playUrl=" + playUrl);
                        if (!TextUtils.isEmpty(playUrl)) {
                            DashManager.instance().setStartTime(mRecord.getStart_time());
                            DashManager.instance().setEndTime(mRecord.getEnd_time());
                            DashManager.instance().initDash(playUrl, DashDecodeController.instance(mMac).getDashCallback(), mVideoMode, playerHandler, true);
                        } else {
                            Toast.makeText(DBKvsEventPlayerActivity.this, getString(R.string.wyze_event_kvs_playback_url_is_null), Toast.LENGTH_SHORT).show();
                            setViewStatus(CONNECT_STATUS_ERROR, false, ERROR_IGNORE);
                            isPlayOver = true;
                            clear();
                            iv_play_icon.setVisibility(View.VISIBLE);
                            AnimLoading.cancel();
                        }
                    } else {
                        Toast.makeText(DBKvsEventPlayerActivity.this, getString(R.string.wyze_kvs_get_url_failed), Toast.LENGTH_SHORT).show();
                        AnimLoading.cancel();
                    }
                }
                break;
                case MessageIndex.DASH_NEED_NEXT_DM: {//fixme:加载下一个dm
                    if (mVideoMode == VIDEO_DASH_LIVING) {
                        if ((boolean) msg.obj) {
                            Log.e(TAG, "CLOUD_GET_KVS_URL_LIVE---->DASH_NEED_NEXT_DM");
                            DashManager.instance().initDash(playUrl, DashDecodeController.instance(mMac).getDashCallback(), mVideoMode, playerHandler, false);
                        }
                    }
                }
                break;
                case MessageIndex.CLOUD_REQUEST_TIMEOUT: {
                    Log.i(TAG, "CLOUD_TIME_OUT ");
                    Toast.makeText(DBKvsEventPlayerActivity.this, R.string.timeout_download_video, Toast.LENGTH_SHORT).show();
                }
                break;
                case MessageIndex.DASH_GET_MPD: {
                    if (MessageIndex.FAIL == msg.arg1) {
                        Toast.makeText(DBKvsEventPlayerActivity.this, "Get MPD info error,error code is " + msg.arg2, Toast.LENGTH_SHORT).show();
                    }
                }
                break;
                case com.HLApi.utils.MessageIndex.DASH_PLAY_OVER: {
                    //TODO show ui
                    if (mVideoMode == VIDEO_DASH_PLAYBACK) {
                        Log.i(TAG, "Play over");
                        String startStr = CommonMethod.getCounterTimeString(DashManager.instance().getDmStartTsInMs() / 1000, "HH:mm:ss");
                        String endStr = CommonMethod.getCounterTimeString(DashManager.instance().getDmEndTsInMs() / 1000, "HH:mm:ss");
                        tv_startTime.setText(startStr.concat(" / ").concat(endStr));
                        tv_alarm_startTime_land.setText(startStr.concat(" / ").concat(endStr));
                        playerHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isPlayOver = true;
                                lastFrameUs = 0;
                                uiForRePlayStop();
                                pausePlay();
                                seekBar.setProgress(0);
                                sb_alarm_seekbar_land.setProgress(0);
                            }
                        }, 1000);
                    }
                }
                break;
                case com.HLApi.utils.MessageIndex.MERGE_VIDEO_STOP: {
                    if (msg.obj != null) {
                        videoFile = new File((String) msg.obj);
                        Log.i(TAG, "merge video succeed,path is " + videoFile.getPath());
                        if (isShare) {
                            isShare = false;
                            share(videoFile);
                        } else {
                            saveVideoToSystem(videoFile, 2);
                            Toast.makeText(DBKvsEventPlayerActivity.this, getString(R.string.save_to_album), Toast.LENGTH_SHORT).show();
                            if (mVideoMode == VIDEO_DASH_PLAYBACK) {
                                //playback
                                if (!iv_play_icon.isSelected()) {
                                    long tsInMs = DashManager.instance().prog2TsInMs(isFullScreen ? sb_alarm_seekbar_land.getProgress() : seekBar.getProgress(), isFullScreen ? sb_alarm_seekbar_land.getMax() : seekBar.getMax());
                                    DashDecodeController.instance(mMac).resumeDashCallBack();
                                    DashManager.instance().resumePlaying(tsInMs);
                                    iv_play_icon.setSelected(false);
                                    hidePlayIcon();
                                } else {
                                    Log.e(TAG, "click download icon,the video has play over !!!");
                                }
                            }
                        }
                    }
                    AnimLoading.cancel();
                }
                break;
                case MessageIndex.DASH_DOWNLOAD_OVER: {
                    if (isMergeVideo) {
                        isMergeVideo = false;
                        DashManager.instance().mergeVideo(systemPath.concat(mMac).concat("/"), mRecord.getEventID().concat(".mp4"));
                    }
                }
                break;
                case com.HLApi.utils.MessageIndex.DASH_LIVE_CHANGE_TO_REPLAY: {
                    Log.e(TAG, "receive live change to replay info");
                    mVideoMode = VIDEO_DASH_PLAYBACK;

                    String startStr = CommonMethod.getCounterTimeString(DashManager.instance().getDmStartTsInMs() / 1000, "HH:mm:ss");
                    String endStr = CommonMethod.getCounterTimeString(DashManager.instance().getDmEndTsInMs() / 1000, "HH:mm:ss");
                    Log.e(TAG, "startTime:" + DashManager.instance().getDmStartTsInMs() + " ,endTime:" + DashManager.instance().getDmEndTsInMs());

                    tv_startTime.setText(startStr.concat(" / ").concat(endStr));
                    tv_alarm_startTime_land.setText(startStr.concat(" / ").concat(endStr));
                    seekBar.setMax((int) DashManager.instance().getDuration());
                    sb_alarm_seekbar_land.setMax((int) DashManager.instance().getDuration());

                    iv_share.setVisibility(View.VISIBLE);
                    iv_alarm_download.setVisibility(View.VISIBLE);
                    uiForRePlayStop();
                    pausePlay();
                    setDurationUI(mVideoMode);
                    playerHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            seekBar.setProgress(0);
                            sb_alarm_seekbar_land.setProgress(0);
                            lastFrameUs = 0;
                        }
                    }, 1000);

                }
                break;
                case com.HLApi.utils.MessageIndex.CLOUD_WATCH_VIDEO_LIMIT: {
                    Log.d(TAG, "观看次数已达上限");
                    Toast.makeText(DBKvsEventPlayerActivity.this, getString(R.string.wyze_event_kvs_playback_url_is_null), Toast.LENGTH_SHORT).show();
                    setViewStatus(CONNECT_STATUS_ERROR, false, ERROR_IGNORE);

                    DashDecodeController.instance(mMac).stopDash();
                    DashDecodeController.instance(mMac).clearCache();
                    iv_play_icon.setVisibility(View.VISIBLE);

                    AnimLoading.cancel();
                }
                break;
                case com.HLApi.utils.MessageIndex.CLOUD_GET_V2_DEVICE_INFO: {
                    if (msg.arg1 == com.HLApi.utils.MessageIndex.SUCCESS) {
                        CameraInfo cameraInfo = (CameraInfo) msg.obj;
                        isOwner = cameraInfo.isOwner();
                    } else {
                        Log.i(TAG, "get device info failed");
                        isOwner = false;
                    }
                }
                break;
                case com.HLApi.utils.MessageIndex.CLOUD_GET_DEVICE_CUSTOM_DATA: {
                    if (msg.arg1 == com.HLApi.utils.MessageIndex.SUCCESS) {
                        if (msg.obj != null) {
                            try {
                                JSONObject object = (JSONObject) msg.obj;
                                JSONArray custom_data_list = object.getJSONArray("custom_data_list");
                                if (custom_data_list != null) {
                                    int length = custom_data_list.length();
                                    for (int i = 0; i < length; i++) {
                                        JSONObject jsonObject = custom_data_list.getJSONObject(i);
                                        String key = jsonObject.optString("data_key");
                                        if (key.equals("DeviceParams")) {
                                            JSONObject data_value = jsonObject.getJSONObject("data_value");
                                            data_value.optString("1");
                                            isHasSDCard = data_value.optString("2").equals("1");
                                        }
                                    }
                                } else {
                                    isHasSDCard = false;
                                    Log.i(TAG, "get custom_data_list is null");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            isHasSDCard = false;
                            Log.i(TAG, "get device custom data is null");
                        }
                    } else {
                        isHasSDCard = false;
                        Log.i(TAG, "get device custom data failed.");
                    }
                }
                break;
                case MSG_HIDE_PORTRAIT_PLAY_ICON: {
                    iv_play_icon.setVisibility(View.GONE);
                    rl_operator.setVisibility(View.GONE);
                }
                break;
            }
        }
    }

    private void saveVideoToSystem(File savedFile, int type) {
        com.HLApi.utils.CommonMethod.saveVideoToSysytem(this, playerHandler, savedFile, type);
    }

    private void receiveFirstIFrame(boolean isDashStream) {
        initCMCPlayer();
        hasReceiveIFrame = true;
        setViewStatus(isDashStream ? CONNECT_STATUS_DASH_PLAY : CONNECT_STATUS_PLAY, false, ERROR_IGNORE);
        isAudioEnable = SPTools.getBooleanValue(DBKvsEventPlayerActivity.this, SPTools.KEY_ALARM_VOICE + mMac, false);
        setAudioEnable(isAudioEnable);
    }

    /**
     * 保持三个视频，多的删除最老的那些
     */

    private void keepThreeVideo() {
        try {
            List<File> fileList = CommonMethod.listFileSortByModifyTime(C.newVideoPath, new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().contains(".mp4");
                }
            });

            Log.i(TAG, "fileList size = " + fileList.size());

            //大于三个 则 删除最老的
            if (fileList.size() > 3) {
                for (int i = 3; i < fileList.size(); i++) {
                    boolean delete = fileList.get(i).delete();
                    if (delete) {
                        Log.i(TAG, "file delete success");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void DecryptionVideo(File file, String pwd) {
        if (file == null) {
            return;
        }
        byte[] bytes = FileToByte(file.getPath());
        byte[] data = DecryptionUtils.getInstance().decryption_file(bytes, pwd);
        createFileWithByte(data, file.getPath());
    }

    private void createFileWithByte(byte[] bytes, String path) {
        File file = new File(path);
        FileOutputStream outputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            bufferedOutputStream.write(bytes);
            bufferedOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
        //通知图库更新
        Uri localUri = Uri.fromFile(file);
        Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
        sendBroadcast(localIntent);
        //保留三个视频
        keepThreeVideo();
        Log.i(TAG, "发送通知，刷新相册");
        playerHandler.sendEmptyMessageDelayed(MSG_PREPARE_PLAY, 2000);
    }

    private byte[] FileToByte(String path) {
        File file = new File(path);
        if (file.isFile()) {
            FileInputStream fis = null;
            ByteArrayOutputStream outputStream = null;
            try {
                fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                outputStream = new ByteArrayOutputStream();
                int len = 0;
                while ((len = fis.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                return outputStream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        } else {
            Log.d(TAG, "文件不存在");
        }
        return null;
    }

//    private void decryptVideo(File videoFile, String pwd) {
//        if (videoFile.isFile()) {
//            FileInputStream fis = null;
//            ByteArrayOutputStream outputStream = null;
//            try {
//                fis = new FileInputStream(videoFile);
//                byte[] buffer = new byte[1024];
//                outputStream = new ByteArrayOutputStream();
//                int len = 0;
//                while ((len = fis.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, len);
//                }
//                byte[] bytes = outputStream.toByteArray();
//                getFile(bytes, videoFile, pwd);
//            } catch (IOException e) {
//                e.printStackTrace();
//            } finally {
//                if (fis != null) {
//                    try {
//                        fis.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                if (outputStream != null) {
//                    try {
//                        outputStream.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//        } else {
//            Log.d(TAG, "文件不存在");
//        }
//    }
//
//    private void getFile(byte[] bytes, File videoFile, String pwd) {
//        byte[] data = DecryptionUtils.getInstance().decryption_file(bytes, pwd);
//        BufferedOutputStream bos = null;
//        FileOutputStream fos = null;
//        File file = null;
//        try {
//            File dir = new File(videoFile.getParent());
//            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
//                dir.mkdirs();
//            }
//            file = new File(videoFile.getParent() + "/" + "tem_" + videoFile.getName());
//            if (file.exists()) {
//                file.delete();
//            }
//            file.createNewFile();
//            fos = new FileOutputStream(file);
//            bos = new BufferedOutputStream(fos);
//            bos.write(data);
//            bos.flush();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (bos != null) {
//                try {
//                    bos.close();
//                } catch (IOException e1) {
//                    e1.printStackTrace();
//                }
//            }
//            if (fos != null) {
//                try {
//                    fos.close();
//                } catch (IOException e1) {
//                    e1.printStackTrace();
//                }
//            }
//        }
//    }

    public static ArrayList<byte[]> audioDataList = new ArrayList<>();

    private void initAudioPlayer() {
        if (mPCMAudioTrack == null) {
            mPCMAudioTrack = new AudioTrack(
                    AudioManager.STREAM_MUSIC,
                    8000,
                    AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    Math.max(AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT) * 3, 10240),
                    AudioTrack.MODE_STREAM);
        } else {
            mPCMAudioTrack.flush();
        }
        try {
            mPCMAudioTrack.play();
            if (playAudioThread == null || playAudioThread.getState() != Thread.State.NEW || playAudioThread.getState() != Thread.State.TERMINATED) {
                playAudioThread = null;
                playAudioThread = new PlayAudioThread(0);
            }
            if (playAudioThread.getState() == Thread.State.NEW || playAudioThread.getState() == Thread.State.TERMINATED) {
                playAudioThread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isAudioEnable = SPTools.getBooleanValue(DBKvsEventPlayerActivity.this, SPTools.KEY_ALARM_VOICE + mMac, false);
        Log.i(TAG, "=====isAudioEnable=======" + isAudioEnable);
        setAudioEnable(isAudioEnable);
    }

    private Track audioTrack = null;

    public boolean getAudioTrack() {
        Movie movie = null;
        Log.i(TAG, "getAudioTrack = " + videoFile.getPath());

        try {
            movie = MovieCreator.build(videoFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "getAudioTrack  MovieCreator build error = " + e.getMessage());
        }
        if (movie == null) {
            return false;
        }
        List<Track> tracks = movie.getTracks();
        for (Track t : tracks) {
            if (t.getHandler().equals("soun")) {
                audioTrack = t;
                long sampleLength = audioTrack.getSamples().get(0).getSize();
//                Log.i(TAG, "samples length" + audioTrack.getSamples().get(0).getSize());
//                Log.i(TAG, "获取到音轨 sampleLength=" + sampleLength);
                if (sampleLength == 160L) {
                    Log.d(TAG, "-----------Decode Audio Data Start ---------");
                    if (audioTrack != null) {
                        int size = audioTrack.getSamples().size();
                        Log.d(TAG, "size=" + size);
                        for (int i = 0; i < size; i++) {
                            try {
                                byte[] g711Data = new byte[160];
                                audioTrack.getSamples().get(i).asByteBuffer().get(g711Data);
                                byte[] result = new byte[g711Data.length * 2];
                                G711Utils.decode(g711Data, 0, g711Data.length, result);
                                if (audioDataList != null && result.length > 0) {
                                    audioDataList.add(result);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        Log.d(TAG, "----------audioDataList----length----" + audioDataList.size());
                        Log.d(TAG, "-----------Decode Audio Data end ---------");
                        return true;
                    } else {
                        Log.d(TAG, "-----------audioTrack is null--------");
                        Log.d(TAG, "-----------Decode Audio Data end ---------");
                    }
                } else {
                    return false;
                }
            }
        }
        return false;
    }

    Runnable updateProgressRunnable = new Runnable() {
        public void run() {
            if (mPlayer != null && mPlayer.isPlaying()) {
//                Log.d(TAG, "updateProgressRunnable current position:" + mPlayer.getCurrentPosition() + ",max:" + mPlayer.getDuration());
                seekBar.setProgress(mPlayer.getCurrentPosition());
                sb_alarm_seekbar_land.setProgress(mPlayer.getCurrentPosition());
                playerHandler.obtainMessage(CHANGE_START_TIME, mPlayer.getCurrentPosition(), -1).sendToTarget();
                if (isUpdateProgress) {
                    long now = SystemClock.uptimeMillis();
                    long next = now + (100 - now % 100);
                    isProgUpdaterRunning = playerHandler.postAtTime(updateProgressRunnable, next);// 每0.5秒监听一次是否在播放视频
                }
            } else {
                isProgUpdaterRunning = false;
            }
        }
    };

    private void runProgUpdater(String tag) {
        Log.d(TAG, "runProgUpdater run, isUpdateProgress=" + isUpdateProgress + "  isProgUpdaterRunning=" + isProgUpdaterRunning + "  tag=" + tag);
        if (isProgUpdaterRunning) {
            return;
        }
        if (isUpdateProgress) {
            updateProgressRunnable.run();
        }
    }

    private String getVideoDurationStr(int videoLengthInMills) {
        String str = "";
        if (videoLengthInMills > 1000) {
            int totalSeconds = videoLengthInMills / 1000;
            int minutes = totalSeconds / 60;
            int seconds = totalSeconds - minutes * 60;
            String minuteString = "";
            String secondString = "";
            if (minutes >= 0 && minutes <= 9) {
                minuteString = "0" + minutes;
            } else {
                minuteString = "" + minutes;
            }
            if (seconds >= 0 && seconds <= 9) {
                secondString = "0" + seconds;
            } else {
                secondString = "" + seconds;
            }
            str = minuteString + ":" + secondString;
        } else {
            str = "00:00";
        }

        return str;
    }

    public void clearSeekbarUpdater() {
        try {
            playerHandler.removeCallbacks(updateProgressRunnable);
            isProgUpdaterRunning = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class PlayAudioThread extends Thread {

        private byte[] audioData = null;
        byte[] pcmSpeakData = new byte[1920];
        private float startPercentage = 0;
        private boolean isPausePlaySound = false, isRunOver = false, isChangedPst = false;
        int res = 0;

        private PlayAudioThread(float startPercentage) {
            this.startPercentage = startPercentage;
            isPausePlaySound = false;
        }

        private void setStartPercentage(float startPercentage) {
            this.startPercentage = startPercentage;
            isChangedPst = true;
            Log.d(TAG, "setStartPercentage=" + startPercentage);
        }

        private boolean isRunOver() {
            return this.isRunOver;
        }

        public void setPause(boolean pause) {
            isPausePlaySound = pause;
        }

        public void run() {
            Log.d(TAG, "-----------PlayAudioThread Thread Start --------isPausePlaySound=" + isPausePlaySound);
            int size = audioDataList == null ? 0 : audioDataList.size();
            int start = (int) (size * startPercentage);
            isRunOver = false;
            Log.d(TAG, "startPercentage=" + startPercentage + "  start=" + start + "  size=" + size);
            for (int i = start; i < size; i++) {
                while (isPausePlaySound) {
                    try {
                        sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (isChangedPst) {
                    i = (int) (size * startPercentage);
                    isChangedPst = false;
                    Log.d(TAG, "change startPercentage=" + startPercentage + "  start=" + start + "  size=" + size + "  i=" + i);
                }
                try {
                    audioData = audioDataList.get(i);
                    if (audioData != null) {
//                        Log.d(TAG, "-----------PlayAudioThread run -------" + audioData.length + "--" + ByteOperator.byteArrayToHexString(audioData, 20));
                        System.arraycopy(audioData, 0, pcmSpeakData, 0, audioData.length);
                        try {
//                            Log.d(TAG, "audio pcmSpeakData length" + pcmSpeakData.length + "mPCMAudioTrack " + mPCMAudioTrack.getSampleRate());
                            res = mPCMAudioTrack.write(pcmSpeakData, 0, audioData.length);
//                            Log.d(TAG, "-----------PlayAudioThread run --------res-" + res + "  i=" + i);
                        } catch (Exception e) {
                            Log.d(TAG, "-----------audio run Exception---------res=" + res + "   e=" + e.getMessage());
                            e.printStackTrace();
                        }
                    } else {
                        Log.d(TAG, "-----------audioByte is null --------");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            isRunOver = true;
            Log.d(TAG, "-----------PlayAudioThread Thread end ---------");
        }

    }


    private void share(File file) {
        isChangePage = true;
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("video/*"); //分享的是视频类型
        String time = CommonMethod.formatDateTimeByLocal(mRecord.getEvent_ts());
        intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(time));
        Uri uri = null;
        if (videoFile != null && videoFile.exists()) {
//            uri = Uri.fromFile(videoFile);
            uri = queryUriForVideo(this, videoFile);
            if (uri == null) {
                uri = insertVideo(videoFile.getPath());
            }
            if (uri == null) {
                uri = Uri.fromFile(file);
            }
            Log.d(TAG + "share", "uri==" + uri.toString());
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(intent, getTitle()));
        }
    }

    /**
     * 插入视频到MediaStore
     */
    private Uri insertVideo(String mediaPath) {
        ContentValues content = new ContentValues(4);
        content.put(MediaStore.Video.VideoColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
        content.put(MediaStore.Video.Media.MIME_TYPE, "video/*");
        content.put(MediaStore.Video.Media.DATA, mediaPath);
        ContentResolver resolver = WpkBaseApplication.getAppContext().getContentResolver();
        return resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, content);
    }

    /**
     * 查找视频文件对应于MediaStore的Uri
     *
     * @param file 视频文件
     * @return
     */

    private Uri queryUriForVideo(Activity activity, File file) {
        int id = getId(activity, file);
        if (id == -1) {
            return null;
        }
        return Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
    }


    private int getId(Activity activity, File f) {
        int id = -1;
        String[] mediaColumns = {MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DATA, MediaStore.Video.Media.TITLE,
                MediaStore.Video.Media.MIME_TYPE,
                MediaStore.Video.Media.DISPLAY_NAME};
        final String where = MediaStore.Video.Media.DATA + "=" + "?";
        Cursor cursor = activity.managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                mediaColumns, where, new String[]{f.getAbsolutePath()}, null);
        if (cursor == null) {
            return -1;
        }
        if (cursor.moveToFirst()) {
            do {
                id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Video.Media._ID));
            } while (cursor.moveToNext());
        }
        return id;
    }

    private boolean getRom() {
        //创建Random类对象
        Random random = new Random();

        //产生随机数
        int number = random.nextInt(RANMAXNUM);
        Log.i(TAG, "getRom = " + number);
        return number == 1;
    }

    private void statisticDuration() {
        long time = System.currentTimeMillis() / 1000;
        long second = time - duration;
        if (duration != -1 && second > 0 && second < 1000) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("duration", second + "");
            map.put("fileId", mRecord.getEventID());
            Log.i(TAG, "statisticDuration  -- map = " + map.toString());
            WyzeStatisticsUtils.logEvent(StatIndex.PID_EVENT, WpkStatisticsAgent.STATISTICS_WYZE, 2, StatIndex.WYZE_EVENT_PLAY_DURATION, second + "", map);
            duration = System.currentTimeMillis() / 1000;//上报之后清掉之前数值
        }
    }

    /**
     * 对门铃mp4文件进行旋转
     */
    private void rotateDBFile(){
        String newFilePath = C.newVideoPath+"db_rotate_"+videoFile.getName();
        if(new File(newFilePath).exists()){
            Log.i(TAG, "new FilePath:"+newFilePath);
            videoFile = new File(newFilePath);
            playerHandler.sendEmptyMessage(MSG_PREPARE_PLAY);

        }else{
            int result = Mp4Editor.rotate270(videoFile.getAbsolutePath(), newFilePath);
            Log.i(TAG, "旋转是否成功:"+result);
            if(result == 0){// 旋转成功
                videoFile = new File(newFilePath);
                playerHandler.sendEmptyMessage(MSG_PREPARE_PLAY);
            }else{
                File tempFile = new File(newFilePath);
                if(tempFile.exists()){
                    tempFile.delete();
                }
            }

        }

    }
}
